快速排序(Quick Sort)

来源:互联网 发布:电脑网络不通怎么办 编辑:程序博客网 时间:2024/05/22 02:05

         快速排序的基本思想是:通过一趟排序将待排记录分割成独立的两部分,其中一部分记录的关键字均比另一部分的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序的目的。

#include <iostream>using namespace std;void Swap(int *L, int i, int j)  {  int temp = L[i];  L[i] = L[j];       L[j] = temp;  }  int Partition(int *L, int low, int high){int pivotkey;pivotkey = L[low];while (low<high){while(low < high && L[high] >= pivotkey){high--;}Swap(L,low,high);while(low < high && L[low] <= pivotkey){low++;}Swap(L,low,high);}return low;}void QSort(int *L, int low, int high){int pivot;if (low < high){pivot = Partition(L,low,high);QSort(L,low,pivot-1);QSort(L,pivot+1,high);}}/*void QuickSort(int *L, int n){QSort(L,0,n);}*/int main(){    int L1[9] = {9,1,5,8,3,7,4,6,2};int L2[9] = {50,10,90,30,70,40,80,60,20};    QSort(L1,0,8);//n=9for (int i = 0; i<9; i++){cout<<L1[i]<<" ";}cout<<endl;getchar();return 0;}
结果:

时间复杂度为:O(N*logN)

相关:

白话经典算法系列之六 快速排序 快速搞定


原创粉丝点击