I don't believe that noone here can (or is willing to?) explain insertion sort. It really isn't that hard. (Well, except perhaps the version above, for it does not work...)
First of all a correct version without error-prone C arrays:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#include <iostream>
#include <iterator>
#include <vector>
int main()
std::vector<int> a; // don't use C arrays...
std::cout<<"Enter number sequence (end with Ctrl-d)"<<std::endl;
std::copy(std::istream_iterator<int,char>(std::cin), // why use a self-written loop? This one is better...
std::istream_iterator<int,char>(), std::back_inserter(a));
int j=0, key=0; // *always* initialize variables
for (int i=1; i<a.size(); ++i) // use pre-increment to avoid unneccessary temorary object
{
key= a[i];
j = i-1;
while((j >= 0) && (a[j] > key))
{
a[j+1] = a[j];
j -= 1;
}
a[j+1]=key;
}
std::cout<<"Sorted sequence:\n";
std::copy(a.begin(), a.end(), std::ostream_iterator<int>(std::cout, "\n")); // another loop avoided...
std::cout<<std::flush;
}
|
(Actually, the two loops still in the code could be avoided by the usage of std::stable_sort, but that is not the point here, I guess...)
In the outer loop an index i is maintained which points to the location in the array a to which the latter is sorted already (in the beginning, the first element of a is sorted obviously, since a single element cannot contain an inversion).
Then, the next element to be inserted into the sorted sequence is stored in key (this is the first element *after* the sorted sequence, indexed by j). In order to insert it into the sorted sequence (in the right place), all elements > key have to be moved to the right one place, in order to make room for the value stored in key. When the right place is found, the inner loop terminates (condition a[j] > key, or we are at the start of a). After a.size()-1 runs of the outer loop, i equals a.size(). Since i is the index to which a is sorted, the sequence is sorted (after showing that this invariant holds true at all times, you may write 'qed' at this point ;-) )