快速排序的C++实现

快速排序是一种比较简单而且排序效果很不错的排序算法,具体的介绍可以看这篇文章“这篇文章"


#include 

using namespace std;

void quicksort(int *data,int start,int end);
void swap(int *data,int i,int j);

int main()
{
    int data[] = {6,1,2,7,9,3,4,5,10,8};
    cout << "before sort,data is" << endl;
    for(int i = 0;i < 10;++i)
        cout << data[i] << " ";
    cout << endl;

    quicksort(data,0,9);
    cout << "After sorted,data is:" << endl;
    for(int i = 0;i < 10;++i)
        cout << data[i] << " ";

    return 0;
}


void quicksort(int *data,int start, int end)
{
    if(start > end)
        return;
    int i = start;
    int j = end;
    int base = data[i];

    while (i < j)
    {
        while(data[j] >= base && j > i)
            --j;
        while(data[i] <= base && i < j)
            ++i;
        if (i < j)
            swap(data,i,j);
    }
    swap(data,start,i);

    quicksort(data,start,i-1);
    quicksort(data,i+1,end);
}


void swap(int *data,int i,int j)
{
    int temp = data[i];
    data[i] = data[j];
    data[j] = temp;
}
posted @ 2015-07-05 20:32  RIO_2607  阅读(298)  评论(0编辑  收藏  举报