您的位置:首页 > 编程语言 > C语言/C++

排序算法C/C++实现_快速排序(Quick Sort)

2014-04-18 09:48 323 查看

快速排序是对气泡排序(Bubble Sort)的一种改进。它的基本思想是,通过一趟排序将待排序记录分割成独立的两部分,其中一部分记录的关键字均比另一部分记录的关键字小,则可分别对两个部分记录继续进行排序,以打到整个序列有序。(数据结构,严蔚敏)

算法实现:#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int Partition(int *arr, int low, int high) {
    
    int randomIndex = low + rand() % (high - low + 1);  //产生随机位置作为枢轴,防止对有序序列排序时速度过慢 
    int temp = arr[low];
    arr[low] = arr[randomIndex];
    arr[randomIndex] = temp;
    
    int pivotkey = arr[low];
    while(low < high) {
        while(low < high && arr[high] >= pivotkey) --high;   
        if(low < high)     
            arr[low] = arr[high];
        while(low < high && arr[low] <= pivotkey) ++low; 
        if(low < high)     
            arr[high] = arr[low];
    }
    
    arr[low] = pivotkey;    
    return low;
  
}

void QuickSort(int *arr, int s, int e) {
     if(s < e) {
          int low = Partition(arr, s, e);
          QuickSort(arr, s, low-1);
          QuickSort(arr, low+1, e);
     }
}

int main() {
    int N = 0;
    while(scanf("%d",&N) != EOF) {  //首先输入待排序序列个数 
        int *arr = (int *)malloc(sizeof(int) * N);
        for(int i=0; i<N; ++i) {
            scanf("%d",&arr[i]);  //依次输入每个带排序元素 
        }
        QuickSort(arr, 0, N-1);   
        for(int i=0; i<N; ++i) {
            printf("%d ",arr[i]);
        }
        printf("\n");
        free(arr);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息