previous | start | next

2.1.24

Here is insertion sort:

    1   
    2     template<typename E>
    3     static void sort(vector<E>& v)
    4     {
    5       for(unsigned int i = 1; i < v.size(); i++) {
    6         // insert v[i] into v[0]...v[i - 1]
    7         int pos = i - 1;
    8         for(int j = i; j > 0 && v[j] < v[j-1]; j--) {
    9           E tmp = v[j];
   10           v[j] = v[j - 1];
   11           v[j - 1] = tmp;
   12         }
   13       }
   14     }

If we first find the smallest element and swap it with v[0], how can we simplify the inner loop?

Same except:



previous | start | next