插入排序,按升序(降序将代码第17行改为
while(i >= 0 && a[i] < key) {
)
1 #include<iostream> 2 #include<string> 3 #include<cstring> 4 using namespace std; 5 6 /** 7 * @desc Insertion sort 8 * 9 * @date 3/28/2015 10 * 11 */ 12 void insertionSort(int *a) { 13 int i = 0, key; 14 for(int j = 1; j < 6; j++) { 15 key = a[j]; 16 i = j - 1; 17 while(i >= 0 && a[i] > key) { 18 a[i+1] = a[i]; 19 i--; 20 } 21 a[i+1] = key; 22 } 23 } 24 25 void main() { 26 int array[6] = {5, 2, 4, 6, 1, 3}; 27 insertionSort(array); 28 for(int i = 0; i < 6; i++) 29 cout<<array[i]<<endl; 30 }