void QuickSortCore(int* data, int first, int last);
int partition(int* data, int first, int last);
void QuickSort(int* data, int length)
{
if(data == NULL || length <= 0) return;
QuickSortCore(data, 0, length-1);
}
void QuickSortCore(int *data, int first, int last)
{
if(first < last)
{
int pivot = partition(data, first, last);
QuickSortCore(data, first, pivot-1);
QuickSortCore(data, pivot+1, last);
}
}
void swap(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
int partition(int* data, int first, int last)
{
//将data[first],data[mid],data[last]三个数中间大的那个交换到data[last]
//并以data[last]作为pivot,即“三数取中”法
int mid = first + (last-first)/2;
if(data[mid] < data[first]) swap(data[mid],data[first]);
if(data[last] < data[first]) swap(data[last],data[first]);
if(data[mid] < data[last]) swap(data[mid],data[last]);
int i = first - 1, j = first;
for(; j < last; j++)
{
if(data[j] > data[last]) continue;
else if(j == i+1) i++;
else swap(data[++i],data[j]);
}
swap(data[++i],data[last]);
return i;
}
数组的快速排序(递归,需要隐性栈空间)
最新推荐文章于 2024-03-27 23:44:50 发布