# 【快速排序二】

/*

41 24 76 11 45 64 21 69 19 36

，往左找比45小的进行交换：
41     24 76*     11 [45] 64     21     69 19 *36
41     24 36     11 45*     64     21     69 19* 76
41     24 36     11 19     64* 21* 69 45 76
[41 24 36     11 19     21] [64 69 45 76]

*/
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>

#define MAX 10
#define SWAP(x, y){int t; t = x; x =y; y = t;}

void quicksort(int [], int, int );

int main(void){
int number[MAX] = {0};
int i, num, flag = 1;
char ch;
srand(time(NULL));
while(flag){
printf("排序前：");
for(i = 0; i < MAX; i++){
number[i] = rand() % 100;
printf("%d ", number[i]);
}

quicksort(number, 0, MAX - 1);
printf("\n排序后：");
for(i = 0; i < MAX; i++){
printf("%d ", number[i]);
}
printf("\n");
printf("是否继续？(y or Y)：");
scanf("%c", &ch);
getchar();
if(ch != 'y' && ch != 'Y'){
flag = 0;
}
}

return 0;
}

void quicksort(int number[], int left, int right){
int i, j, s;
if(left < right){
s = number[(left + right) / 2];
i = left - 1;
j = right + 1;
while(1){
while(number[++i] < s);    //向右找
while(number[--j] > s);    //向左找
if(i >= j){
break;
}
SWAP(number[i], number[j]);
}

quicksort(number, left, i - 1);        //对左边进行递回
quicksort(number, j + 1, right);    //对右边进行递回
}
}

posted @ 2017-02-11 16:00  天秤libra  阅读(692)  评论(0编辑  收藏