快速排序(quick-sort)

来源:互联网 发布:sql server 变量赋值 编辑:程序博客网 时间:2024/06/02 18:39

今儿闲着没事儿看了一眼c++primer,开到一段代码是用来排序的,但是看了好长时间没看出来使用的什么排序方法。最后终于弄明白原来是快速排序(quick-sort)。看来大二时候学的数据结构忘得差不多了。既然快速排序这么陌生,今儿就再复习一遍吧。

1.快速排序的基本原理

快速排序是一种“分治算法”(divide-and-conquer algorithm)
  • 选取一个元素,称作P(the pivot)
  • 从新安排元素到三个“子块”中
  1. 将小于或等于P(<=p)的元素安排到左边“子块”(the left block S1)
  2. P单独占中间“子块”(the middle block)
  3. 将大于P(>=P)的元素安排到右边“子块”(the right block S2)
  • 分别在左右“子块”上递归调用上面过程,得到{quick_sort(s1),P,quick_sort(s2)}


2.例子

下面的图例说明了执行一次partition的过程:


3.复杂度分析

  1. 最坏情况下(元素已经排好序):
             选取第一个元素作为P(pivoT)。quit_sort每执行一次partition,就会消耗时间O(N),所以有:
             
            由上面等式得到时间复杂度为O(N^2)
       2.最好情况下:
P(pivot)将元素均等地分到左右两个“子块”
这时有:
所以这时的时间复杂度为O(N*logN)

4.测试代码

/**  *using template function implement quick_sort  *  * edit by jianyong-lee  * 2014/10/6 southwest university chongqing  * */#include <iostream>// using namespace std;template <class T>T min(const T &a,const T &b){    return a<b?a:b;}template <class T>void swap(T &a,T &b){    T temp=a;    a=b;    b=temp;}template <class T>void quick_sort(T *a,int low,int high){    if(low<high)    {        int lo=low;        int hi=high+1;        T elem=a[lo];        for(;;)        {            while(min(a[++lo],elem)!=elem && lo<high);            while(min(a[--hi],elem)==elem && hi>low);            if(lo<hi)            {                swap(a[lo],a[hi]);            }            else            {                break;            }        }        swap(a[low],a[hi]);        quick_sort(a,low,hi-1);        quick_sort(a,hi+1,high);    }}int main(){    int test_array[]={2,0,1,4,9,5};    quick_sort(test_array,0,5);    for(int i=0;i<6;i++)    {        std::cout<<test_array[i]<<" ";    }    std::cout<<std::endl;    std::cout << "Hello World!" << std::endl;    return 0;}



0 0
原创粉丝点击