插入排序, O(n^2), 从头到尾, 将较小的放在前面
/* insertion sort ascending order */ #include <stdio.h> int main() { int n, array[1000], c, d, t; printf("Enter number of elements "); scanf("%d", &n); printf("Enter %d integers ", n); for (c = 0; c < n; c++) { scanf("%d", &array[c]); } for (c = 1 ; c <= n - 1; c++) { d = c; while ( d > 0 && array[d] < array[d-1]) { t = array[d]; array[d] = array[d-1]; array[d-1] = t; d--; } } printf("Sorted list in ascending order: "); for (c = 0; c <= n - 1; c++) { printf("%d ", array[c]); } return 0; }
冒泡排序, O(n^2), 将较大的放在后面。
/* Bubble sort code */ #include <stdio.h> int main() { int array[100], n, c, d, swap; printf("Enter number of elements "); scanf("%d", &n); printf("Enter %d integers ", n); for (c = 0; c < n; c++) scanf("%d", &array[c]); for (c = 0 ; c < ( n - 1 ); c++) { for (d = 0 ; d < n - c - 1; d++) { if (array[d] > array[d+1]) /* For decreasing order use < */ { swap = array[d]; array[d] = array[d+1]; array[d+1] = swap; } } } printf("Sorted list in ascending order: "); for ( c = 0 ; c < n ; c++ ) printf("%d ", array[c]); return 0; }