sort.c #include <stdio.h> //直接选择排序(选择排序) void select_sort(int *a, int len) { int i, j, temp, addr; for(i = 0;i < len;i++) { temp = a[i]; addr = i; for(j = i;j < len;j++) { if(a[j] < temp) { temp = a[j]; addr = j; } } a[addr] = a[i]; a[i] = temp; } } //快速排序(交换排序) void quick_sort(int *a, int low, int high) { int i, j, pivot; if(low < high) { pivot = a[low]; i = low; j = high; while(i < j) { while(i < j && a[j] > pivot) j--; if(i < j) a[i++] = a[j]; while(i < j && a[i] < pivot) i++; if(i < j) a[j--] = a[i]; } a[i] = pivot; quick_sort(a, low, i - 1); quick_sort(a, i + 1, high); } } //冒泡排序(交换排序) void bubble_sort(int *a, int len) { int i, j, exchange, temp; for(i = 0;i < len - 1;i++) { exchange = 0; for(j = len - 1;j > i;j--) { if(a[j] < a[j - 1]) { temp = a[j]; a[j] = a[j- 1]; a[j -1] = temp; exchange = 1; } } if(exchange == 0) { return; } } } //希尔排序(插入排序) void shell_sort(int *a, int len) { int h, i, j, temp; for(h = len / 2;h > 0;h = h / 2) { for(i = h;i < len;i += h) { temp = a[i]; for(j = i - h;j >= 0 && a[j] > temp; j -= h) { a[j + h] = a[j]; } a[j + h] = temp; } } } //直接插入排序 void insert_sort(int *a, int len) { int i, j, temp; for(i = 1;i < len;i++) { temp = a[i]; for(j = i - 1;j >= 0 && a[j] > temp;j--) { a[j + 1] = a[j]; } a[j + 1] = temp; } } void print_array(int *a, int len) { int i; for(i = 0;i < len;i++) { printf("%d ", a[i]); } printf("/n"); } int main() { int a[] = {4,1,5,6,3,9,8,0,7,2}; print_array(a, 10); //insert_sort(a, 10); //shell_sort(a, 10); //bubble_sort(a, 10); //quick_sort(a, 0, 9); select_sort(a, 10); print_array(a, 10); }