【数据结构】【内部排序总结(C++)之快速排序】

网址:  https://www.cnblogs.com/dreamer123/p/9519498.html

  1. 起泡排序(冒泡排序Bubble Sort)
  • 进行若干趟排序,第i趟起泡排序是将前n-i+1个记录中的最大记录“交换”到第n-i+1的位置上。具体实现规则为:首先比较第一个记录的关键字和第二个记录的关键字,若大于,则交换;然后比较第二个记录的关键字和第三个记录的关键字,若大于,则交换,,,,以此类推,直至第n-i个记录和第n-i+1个记录进行过比较(交换)为止。
  • 平均时间复杂度:O(N2); 稳定性:是。
  • 整个排序过程并不一定需要n-1趟,当在一趟排序过程中,没有进行过记录交换(即序列已成有序状态),即可停止起泡排序。(该机制可以通过一个定义flag变量实现)。
  • 代码:
    void BubbleSort(int a[])
    {
        cout<<"Call BubbleSort fun!"<<endl;
        cout<<"before:";
        for(int i=0; i<N; i++)
            cout<<" "<<a[i];
        cout<<endl;
    
        for(int i=0; i<N-1 ; i++)
        {
            bool flag=false;
            for(int j=0; j<N-i-1; j++)
            {
                if(a[j]>a[j+1])
                {
                    flag=true;
                    int temp=a[j];
                    a[j]=a[j+1];
                    a[j+1]=temp;
                }
            }
        }
        cout<<"after:";
        for(int i=0; i<N; i++)
            cout<<" "<<a[i];
        cout<<endl;
    }
    

      

  • 运行结果截图:

2. 快速排序:

  • 对冒泡排序的一种改进:从待排序记录中选取一个记录(作为枢轴pivot或支点),将pivot放在“正确的”位置,并且小于pivot的记录放在pivot左边(不一定有序),大于pivot的记录放在pivot右边。从而将待排记录分割成独立的两部分,其中一部分的记录的关键字均比另一部分记录的关键字都小。
  • 代码:
    #include<iostream>
    using namespace std;
    const int N=10;
    int Partition(int a[],int low, int high)
    {
        int pivotkey=a[low];
        while(low<high)
        {
            while(low<high && a[high]>=pivotkey)
                high--;
            a[low]=a[high];
    
            while(low<high && a[low]<=pivotkey)
                low++;
            a[high]=a[low];
        }
        a[low]=pivotkey;
        return low;
    }
    void QSort(int a[],int low,int high)
    {
        if(low<high)
        {
            int pivotloc = Partition(a,low, high);
            QSort(a,low,pivotloc-1);
            QSort(a,pivotloc+1,high);
        }
    }
    int main()
    {
        int a[N]={5,6,4,2,1,3,10,2,18,9};
        QSort(a,0,9);
        cout<<"after quick sort:";
        for(int i=0;i<N;i++)
            cout<<" "<<a[i];
        cout<<endl;
        return 0;
    }
    

      

  • 运行结果:
  • 平均时间复杂度:O(nlnn) 最坏时间复杂度:O(N2)【初始记录关键字有序或基本有序时的情况,退化为起泡排序】;稳定性:否

 

posted @ 2018-08-22 18:12  dreamer123  阅读(564)  评论(0编辑  收藏  举报