快速排序算法(C++实现)

来源:互联网 发布:flex java 做什么的 编辑:程序博客网 时间:2024/06/06 23:50
快速排序(Quicksort)是对冒泡排序的一种改进。
快速排序由C. A. R. Hoare在1962年提出。它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
时间复杂度O(nlogn)
空间复杂度O(n)

void swap(double &a, double &b){    double temp = a;    a = b;    b = temp;}int Partition(double *number, int begin, int end){    double temp = number[end];    int ii = begin, jj = end - 1;    while (true)    {        while (number[ii] < temp)        {            ii++;            if (ii == end)            {                break;            }        }        while (number[jj] > temp)        {            jj--;            if (jj == begin)            {                break;            }        }        if (ii < jj)        {            swap(number[ii], number[jj]);        }        else        {            break;        }    }    swap(number[ii], number[end]);    return ii;}void QuickSort(double* number, int begin, int end){    if (begin < end)    {        int q = Partition(number, begin, end);        QuickSort(number, begin, q - 1);        QuickSort(number, q + 1, end);    }}//Sort the number with quick sort algorithm.int SortAlgHao::SortWithQick(){    int error = this->Validation();    if (error != 0)    {        return -1;    }    QuickSort(this->GetNumber(), 0, this->GetSize() - 1);    return 0;}

void main(){    int n = 10;    double *number = new double[10];    for (int ii = 0; ii < n; ii++)    {        number[ii] = rand() % 101;    }
SortAlgHao sortInstance;   sortInstance.SetSize(n);   sortInstance.SetNumber(number);
sortInstance.SortWithQick();
}


0 0
原创粉丝点击