算法思想:
- 从数组中抽出一个元素作为基数v(我们称之为划界元素),一般是取第一个、最后一个元素或中间的元素
- 将剩余的元素中小于v的移动到v的左边,将大于v元素移动到v的右边
- 对左右两个分区重复以上步骤直到所有元素都是有排序好。
方法一:
int Partition(int data[],int low,int high)
{
int first=low,last=high;
//set the first value as the pivot
int pivot=data[first];
while (first<last)
{
//check from the last back to first to find a value smaller than pivot
while (first < last && data[last] >= pivot)
last--;
//set the last value with first;
if(first<last)
data[first] = data[last];
//check from the first to last to find the value larger than pivot
while (first < last && data[first]<= pivot)
first++;
//set the last value to first
if(first<last)
data[last]=data[first];
}
//put the pivot value to the first
data[first] = pivot;
return first;
}
void QuickSort(int data[],int low,int high)
{
if (low>high) return;
int first=Partition(data, low, high);
if(first > low)
QuickSort(data,low,first-1);
if(first < high)
QuickSort(data,first+1,high);
}
方法二:
void Swap(int* pLow, int* pHigh)
{
int temp = *pHigh;
*pHigh = *pLow;
*pLow = temp;
}
int RandomInRange(int low, int high)
{
int r;
r = rand()%(high - low + 1) + low;
return r;
}
int Partition(int data[], int low, int high)
{
if(data == nullptr || low < 0 || high < 0 || low < high)
return;
int pivot = RandomInRange(low, high);
Swap(&data[pivot], &data[high]);
int left = low -1;
for(pivot = low; pivot < high; ++pivot)
{
if(data[pivot] < data[high])
{
++left;
if(left != pivot)
swap(&data[pivot], &data[left]);
}
}
++left;
Swap(&data[left], &data[high]);
return left;
}
void QuickSort(int data[], int low, int high)
{
if(low == high)
return;
int index = Partition(data, low, high);
if(index > low)
QuickSort(data, low, index -1);
if (index < high)
QuickSort(data, index + 1, high);
}