/* file insertionSort.h */ // code by bds, 2/00 #ifndef __INSERTIONSORT__ #define __INSERTIONSORT__ #include //#include #include "iterator_traits" /* Insertion Sort is written to take a pointer to the beginning of the array to be sorted and a pointer to the position just beyond the last item in the array to be sorted. This convention is used throughout the C++ Standard Template Library and applies to other "containers" than arrays as well. This is generic programming, because the type of elements in the array can be any type for which the operator "<=" is defined. To achieve the generic property, the pointer type is a template parameter to the function. We use the name Iterator for the pointer type to be consistent with STL usage. All we actually assume about this type is that the pointer arithmetic operations are valid on objects of type Iterator and that the unknown class pointed to by dereferencing iterators has <= defined. */ template // think "pointer" void insertionSort(Iterator b, Iterator e) // The items in positions [b .. e) to be permuted into sorted order. { for (Iterator j = b+1; j < e; ++j) // invariant: range [b .. j) is sorted. { typedef typename iterator_traits::value_type Key_type; Key_type key = *j; Iterator i; i = j-1; for ( i = j-1; i >= b && key <= *i ; --i ) { *(i+1) = *i; // after copy the invariant is: // 1. [b .. i) is sorted with entries no larger than key // 2. [(i+1) .. j] is sorted with entries greater than key // 3. key is missing from the array // 4. *i is a copy of *(i+1) } *(i+1) = key; } // Now [b .. j) is in order and j = e. // thus [b .. e) is sorted as required. } #endif