What you've just described is selection sort, where you select the minimum element from an array and append that onto an array that you're growing.
Insertion sort takes out the first element of the remaining elements and inserts it into the right place. To sort [2 7 3 9 4], you'd sort in the following fashion, where the list on the left is the sorted list that we're building, and the list on the right is the unsorted list we're taking elements from:
[] [2 7 3 9 4]
-- take the 2 and insert it 'in the right place'
[2] [7 3 9 4]
-- take the 7 and insert it 'in the right place'
[2 7] [3 9 4]
-- take the 3 and insert it 'in the right place'
[2 3 7] [9 4]
-- take the 9 and insert it...
[2 3 7 9] [4]
-- take the 4 and insert it...
[2 3 4 7 9] []
-- we're done!
And the sorted list becomes [2 3 4 7 9].
Now, I've been using the word 'list' instead of array, but that's only because I'm speaking abstractly. You can do an insertion sort on an array, in the fashion described above, in-place. Instead of changing the sizes of two 'lists' (whatever that means in the context of programming), you can simply walk an index through the array, from 0 to the size of the array. The part of the array before the index is sorted, and the part of the array after the index is the unsorted part.
For example, above, after you've taken the 3 and inserted it into the sorted portion, the array will look like [2 3 7 9 4], and the index will currently be 3, so the next element you take out will be 9.
Last edited by Rashakil Fol; Jun 28th, 2007 at 9:03 am.
Reputation Points: 1135
Solved Threads: 172
Super Senior Demiposter
Offline 2,479 posts
since Jun 2005