插入排序:
插入排序属于原地排序(sorted in place),使用的是增量(incremental)方法。
排序从第二个元素开始遍历。在排好序的子数组A[1 .. j -1]中,将元素A[j]插入,形成排好序的子数组A[1 .. j];然后,重复此操作,直到整个数组有序。
使用for循环实现的升序插入排序:
void insertion_sort_asc(int arr[], int len) { if (len <= 0) throw "The length of input array is less than one."; if (len == 1) return; int key; for (int i = 1; i < len; i++) { key = arr[i]; int j; for (j = i; j > -1; j--) { if (arr[j - 1] <= key) break; arr[j] = arr[j - 1]; } arr[j] = key; show(arr, 6); } }
使用while循环实现的升序插入排序:
void insertion_sort_asc_with_while(int a[], int len) { if (len <= 0) throw "The length of input array is less than one."; if (len == 1) return; int key; for (int i = 1; i < len; i++) { key = a[i]; int j = i - 1; while ((j > -1) && (key < a[j])) { a[j + 1] = a[j]; j--; } a[j + 1] = key; show(a, len); } }
使用for循环实现的降序插入排序:
void insertion_sort_des(int arr[], int len) { if (len <= 0) throw "The length of input array is less than one."; if (len == 1) return; int key; for (int i = 1; i < len; i++) { key = arr[i]; int j; for (j = i - 1; j >= 0; j--) { if (arr[j] > key) break; arr[j + 1] = arr[j]; } arr[j + 1] = key; show(arr, len); } }
show函数的定义如下:
void show(int arr[], int len) { for (int i = 0; i < len; i++) cout << arr[i] << " "; cout << endl; }
测试代码:
int main() { int a[] = { 1, 4, 2, 7, 10, 5 }; //insertion_sort_asc(a, 6); insertion_sort_asc_with_while(a, 6); //insertion_sort_des(a, 6); show(a, 6); return 0; }
测试结果:
时间: 2024-11-19 23:07:40