快速排序
在一堆数中选取一个主元,以主元为中心将这堆数分为大小两部分,对这两部分递归调用快排,最后当规模最够小的时候(小于预设的阈值CutOff)将使用简单排序(如插入排序)。
/*快速排序*/
//取主元 get pivot
long Median3(long a[], long Left, long Right)
{
int Center = (Right +Left)/2;
if (a[Left] > a[Center])
Swap(&a[Left] , &a[Center]);
if (a[Left] > a[Right])
Swap(&a[Left], &a[Right]);
if (a[Center] > a[Right])
Swap( &a[Center] , &a[Right]);
Swap(&a[Center], &a[Right - 1]);//把Povit藏到Right-1
return a[Right - 1];
}
//快速排序
void QuickSort(long a[], int Left, int Right)
{
long Pivot;//主元
int i, j;
int CutOff = 10e2;
if (CutOff <= Right - Left)
{
Pivot = Median3(a, Left, Right);
i = Left; //左边指针
j = Right - 1; //右边指针
for (;;)
{
while (a[++i] < Pivot) {
}
while (a[--j] < Pivot) {
}
if (i < j)
Swap(&a[i], &a[j]);
else
break;
}
Swap(&a[i], &a[Right - 1]); //Pivot 落位
QuickSort(a, Left, i - 1);
QuickSort(a, i + 1, Right);
}
else
Insertion_sort(a+Left, Right - Left+1);
}
//统一接口
void Quick_sort(long a[],int N)
{
QuickSort(a, 0, N - 1);
}
/*快速排序结束*/
快排c++背诵版:
class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
int n = nums.size();
quick_sort(nums,0,n-1,n);
return nums;
}
void quick_sort(vector<int>& nums,int left,int right,int n)
{
if(left < right) //分裂到最小单位即停止
{
int pivotpos = partition(nums,left,right);
quick_sort(nums,left,pivotpos-1,n);
quick_sort(nums,pivotpos+1,right,n);
}
}
int