快速排序

来源:互联网 发布:linux权限表示 编辑:程序博客网 时间:2024/05/29 10:57

起泡排序

#include <iostream>using namespace std;void BubbleSort(int * arr,const int size){    int tmp =0 ;    for (int i =0 ;i<size ;i++)        for (int j=i+1;j<size ;j++)        {            if(arr[i]>arr[j])            {                tmp =arr[i];                arr[i] = arr[j];                arr[j] = tmp ;            }        }}void output(int *a, int len){    for(int i = 0; i < len; ++i)    {        cout << a[i] << " ";    }    cout << endl;}int main(){    int a[] = {6, 9, 1, 3, 6, 8, 9, 4};    int len =  sizeof(a) / sizeof(int);    output(a, len);    BubbleSort(a,len);    output(a, len);}

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

#include <iostream>using namespace std;int Partition(int *a, int low, int high){    if (low <= high)    {        int pivotkey = low;        for(int i = low+1; i <= high; ++i)        {            if(a[i] <= a[low])            {                swap(a[pivotkey+1], a[i]);                ++pivotkey;            }        }        swap(a[low], a[pivotkey]);        return pivotkey;    }}void QSort(int *a, int low, int high){    if (a == NULL || low >= high)        return;    int pivotkey = Partition(a, low, high);    QSort(a, low, pivotkey-1);    QSort(a, pivotkey+1, high);}void output(int *a, int low){    for(int i = 0; i < low; ++i)    {        cout << a[i] << " ";    }    cout << endl;}int main(){    int a[] = {6, 9, 1, 3, 6, 8, 9, 4};    int len =  sizeof(a) / sizeof(int);    output(a, len);    QSort(a, 0, len-1);    output(a, len);}
0 0