快速排序C语言实现
这里我实现了一个quick函数,它的类型为空,第一个参数为要排序的数组的首地址,第二个参数为该数组的长度。
#include <stdio.h> #define N 10 int* p; void quick(int* arr, int length) { int i,j,a,temp; i = 0; j = length - 1; a = arr[0]; while(i != j) { //j move while(i != j && arr[j] >= a) { j--; } if(i == j) { break; } //i move do{ i++; }while(i != j && arr[i] < a); if(i == j) { break; } temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; printf("==>"); for (int i = 0; i < N; i++) { printf("%d ", p[i]); } printf("\n"); if(i > 1) { quick(&arr[0], i); } if((length - 1 - i) > 1) { quick(&arr[i+1], length - 1 - i); } } int main() { int array[N] = {5,4,6,2,7,8,1,10,9,3}; p = array; for (int i = 0; i < N; i++) { printf("%d ", array[i]); } printf("\n"); quick(array, N); for (int i = 0; i < N; i++) { printf("%d ", array[i]); } printf("\n"); return 0; }
输出结果: