常见排序算法C语言代码
以下代码亲测可用
#include <stdio.h> void insertsort(int a[], int n)//插入排序 { int temp = 0; int j = 0, i = 0; for (i = 1; i < n; i++) { temp = a[i]; for (j = i - 1; i >= 0 && a[j] > temp; j--) { a[j + 1] = a[j]; //注意 } a[j + 1] = temp; } } void bubblesort(int a[], int n)//冒泡 { int i, j; int temp; for (i = n; i > 0; i--) //注意 { int flag = 1; for (j = 1; j < i; j++) //注意 { if (a[j] < a[j - 1]) { temp = a[j]; a[j] = a[j - 1]; a[j - 1] = temp; //注意temp flag = 0; } } if (flag == 1) break; } } void quicksort(int a[], int low, int high)//快速排序 { int i = low, j = high; int temp = a[low]; if (low < high) { while (i < j) { while (i < j && a[j] > temp) j--; if (i < j) { a[i] = a[j]; i++; } while (i < j && a[i] < temp) i++; if (i < j) { a[j] = a[i]; j--; } } a[i] = temp; quicksort(a, low, i - 1); quicksort(a, i + 1, high); } } void adjust(int a[], int start, int end) { int temp = a[start]; int cur = start; int leaf = start * 2 + 1; for (; leaf <= end; cur = leaf, leaf = leaf * 2 + 1) //注意等于 可能最后的叶子是左边的 { if (leaf < end && a[leaf] < a[leaf + 1]) //最后的叶子是左边的那么久不能++了 leaf++; if (temp < a[leaf]) { a[cur] = a[leaf]; a[leaf] = temp; } else break; } } void headsort(int a[], int n)//堆排序 { int i, temp; for (i = n / 2 - 1; i >= 0; i--) { adjust(a, i, n - 1); } for (i = n - 1; i > 0; i--) { temp = a[i]; a[i] = a[0]; a[0] = temp; adjust(a, 0, i - 1); } } void selectsort(int a[], int n)//选择 { int t; int i; int j; for (i = 0; i < n - 1; i++) { t = i; //注意 for (j = i + 1; j < n; j++) { if (a[j] < a[t]) t = j; } int temp; temp = a[t]; a[t] = a[i]; a[i] = temp; } } int main() { int a[5] = {10, 11, 5, 2, 3}; selectsort(a, 5); for (int i = 0; i < 5; i++) { printf("%d-", a[i]); } return 0; }