C语言写一个快速排序
C语言写一个快速排序(Quick sort)
快速排序
#include <stdio.h>
void swap(int *a, int *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
void qsort(int *nums, int left, int right) {
if(left>=right) return;
int l = left+1; /* left */
int r = right; /* right */
int key = nums[left];
while(1){
while(l <= right){
if(nums[l] > key) break;
l++;
}
while(r > left){
if(nums[r] < key) break;
r--;
}
if(l > r) break;
swap(&nums[l], &nums[r]);
}
swap(&nums[left], &nums[r]); /* swap key */
qsort(nums, left, r - 1);
qsort(nums, r + 1, right);
}
#define SIZE 10 /* array size */
int main(void){
int array[SIZE] = {69, 87, 64, 67, 79, 85, 96, 29, 44, 93};
qsort(array, 0, SIZE - 1);
for(int i = 0; i < SIZE; i ++){
printf("%d ", array[i]);
if( i == 9) printf("\n");
}
}