快速排序一般的写法,教科书上很详细,这里介绍作者的写法。
程序如下:
#include<iostream>
#include<stack>
using namespace std;
void swap(int *value1, int *value2)
{
int temp = *value1;
*value1 = *value2;
*value2 = temp;
}
int partition(int data[],int length,int start,int end)
{
if (NULL == data || length <= 0 || start < 0 || end >= length)
throw exception("Invalid Data!");
int small = start - 1;
for (int index = start; index < end; index++)
{
if (data[index] <= data[end])
{
small++;
if (small != index)
swap(&data[index],&data[small]);
}
}
small++;
swap(&data[small],&data[end]);
return small;
}
void QuickSort(int data[], int length, int start, int end)
{
if (start == end)
return;
int index = partition(data,length,start,end);
if (start < index)
QuickSort(data, length, start, index-1);
if (index < end)
QuickSort(data, length, index+1, end);
}
int main()
{
int data[] = {5,7,2,4,9,3,8,4,1};
QuickSort(data,9,0,8);
for (int i = 0; i < 9; i++)
{
cout << i << " ";
}
return 0;
}