快速排序算法

来源:互联网 发布:彩票算法 编辑:程序博客网 时间:2024/06/10 19:58

快速排序算法
相对于书上的快速排序算法,本程序段的改进在于体现如下:
书上在对数组中数据划分区域时采用整体后移的方法,这种数组这种结构中操作会会损耗很多时间。所以本代码的改进之处就在于划分区域时采用大数区域的首尾直接与小数进行交换的方法,节省了对数组进行后移操作所需要的时间。
本段代码使用了模板,对于不懂模板的同学可以直接将T当作我们常见的一种数据类型(int、double…)就好。

#include <ctime>#include <cstdlib>#include <iostream>using namespace std;template<typename T>class QuickSort{private:    void Recursion(T* arr,int startIndex, int lastIndex)    {        if(startIndex >= lastIndex) return ;        int minIndex = startIndex;        int maxIndex = startIndex;        int cmpIndex = lastIndex;        for(int i = startIndex; i < lastIndex; i++)        {            if(*(arr + i) < *(arr + cmpIndex))            {                T temp = *(arr + maxIndex);                *(arr + maxIndex) = *(arr + i);                *(arr + i) = temp;                ++maxIndex;            }        }        //下面四行本来可以并入到上面循环中去,但是为了减少循环次数,所以就把它单独取出来了,却显得代码冗余。        T temp = *(arr + maxIndex);        *(arr + maxIndex) = *(arr + cmpIndex);        *(arr + cmpIndex) = temp;        ++maxIndex;        Recursion(arr,minIndex,maxIndex-2);        Recursion(arr,maxIndex,lastIndex);    }public:    QuickSort(T* arr, int len)    {        Recursion(arr,0,len-1);    }};int main(){    srand(time(0));    int arr[60] = {0};    cout << "排序前:" << endl;    for(int i = 0; i < 60; ++i)    {        arr[i] = (int)(rand()%(1000));        cout << arr[i] << " ";    }    cout << "\n排序后:" << endl;    QuickSort<int> t(arr,60);    for(int i = 0; i < 60; ++i)    {        cout << arr[i] << " ";    }}
0 0
原创粉丝点击