交换排序—快速排序(Quick Sort)

来源:互联网 发布:淘宝客服接待用语 编辑:程序博客网 时间:2024/06/06 03:21

基本思想:

1)选择一个基准元素,通常选择第一个元素或者最后一个元素,

2)通过一趟排序讲待排序的记录分割成独立的两部分,其中一部分记录的元素值均比基准元素值小。另一部分记录的 元素值比基准值大。

3)此时基准元素在其排好序后的正确位置

4)然后分别对这两部分记录用同样的方法继续进行排序,直到整个序列有序。

快速排序是通常被认为在同数量级(O(nlog2n))的排序方法中平均性能最好的。但若初始序列按关键码有序或基本有序时,快排序反而蜕化为冒泡排序。为改进之,通常以“三者取中法”来选取基准记录,即将排序区间的两个端点与中点三个记录关键码居中的调整为支点记录。快速排序是一个不稳定的排序方法。

#include<iostream>#include<string>using namespace std;void print(int a[], int n){      for(int j= 0; j<n; j++){          cout<<a[j] <<"  ";      }      cout<<endl;  }  void swap(int &a,int &b){    int tmp=a;    a=b;    b=tmp;}int partion(int a[],int low,int high){    int privotekey=a[low];    while(low < high){        while(a[high] > privotekey) high--;        swap(a[low],a[high]);        while(a[low]< privotekey) low++;        swap(a[low],a[high]);    }    print(a,10);    return low;}void quickSort(int a[],int low,int high){    if(low < high){        int privotekey=partion(a,low,high);//每次把low位置的值作为基准值        quickSort(a,low,privotekey-1);        quickSort(a,privotekey+1,high);    }}int main(){      int a[10] = {3,1,5,7,2,4,9,6,10,8};      cout<<"初始值:";      print(a,10);      quickSort(a,0,9);      cout<<"结果:";      print(a,10);  }  

初始值:3 1 5 7 2 4 9 6 10 8
2 1 3 7 5 4 9 6 10 8
1 2 3 7 5 4 9 6 10 8
1 2 3 6 5 4 7 9 10 8
1 2 3 4 5 6 7 9 10 8
1 2 3 4 5 6 7 9 10 8
1 2 3 4 5 6 7 8 9 10
结果:1 2 3 4 5 6 7 8 9 10