【快速排序三】

 

 

/*
快速排序法三 
说明:
之前说过轴的选择是快速排序法的效率关键之一 , 在这边的快速排序法的轴选择方式更加快了快速排序法的效率,它是来自演算法
名书 Introduction toAlgorithms 之中
*/
#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;}

int partition(int [], int, int);
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; 
}

int partition(int number[], int left, int right){
    int i, j, s;
    
    s = number[right];
    i = left - 1;
    
    for(j = left; j < right; j++){
        if(number[j] <= s){
            i++;
            SWAP(number[i], number[j]);
        }
    }
    
    SWAP(number[i + 1], number[right]);
    return i+1;
}

void quicksort(int number[], int left, int right){
    int q;
    
    if(left < right){
        q = partition(number, left, right);
        quicksort(number, left, q - 1);
        quicksort(number, q + 1, right);
    }
} 

 

运行结果:

 

posted @ 2017-02-11 15:59  天秤libra  阅读(601)  评论(0编辑  收藏