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:
- Do one pass to find the minimum and put it in position 0.
- Then the code can just be:
void sort(E[] a) { /* insert code here to find the minimum and swap it with a[0] */ for(int i = 1; i < a.length; i++) { int j = i; while(v[j] < v[j - 1]) { swap(v, j, j - 1); } }