用插入排序法为下列数组排序:
[87, 48, 64, 19, 30, 82, 50, 15, 73, 22, 68, 4, 93, 36, 80, 91, 53, 10, 27]
插入排序(Insertion Sort):通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。插入排序在实现上,通常采用in-place排序(即只需用到O(1)的额外空间的排序)。
#include <stdio.h> void insertionSort(int arr[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } int main() { int arr[] = {87, 48, 64, 19, 30, 82, 50, 15, 73, 22, 68, 4, 93, 36, 80, 91, 53, 10, 27}; int n = sizeof(arr) / sizeof(arr[0]); insertionSort(arr, n); printf("Sorted array: \n"); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; }