#include <iostream>
using namespace std;
int Cutoff = 50;<span style="white-space:pre"> </span>//阈值(可自己调整),低于该阈值使用插入排序更加快捷
void swap(int *a, int *b){
int temp = *b;
*b = *a;
*a = temp;
}
void InsertionSort(int A[],int left,int right)
{
for (int i=left-1; i<=right; i++)
{
int inserter = A[i];
int index = i;
for ( ;index > 0 && A[index-1] > inserter;index--)
A[index] = A[index-1];
A[index] = inserter;
}
}
int Median(int A[], int left, int right){<span style="white-space:pre"> </span>//选主元,取头、中、尾的中位数作为主元
int Center = ( left + right ) / 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] ); <span style="white-space:pre"> </span>//将主元藏在倒数第二位,便于中间的数排序
return A[right - 1];
}
void Quicksort(int A[], int left, int right){ <span style="white-space:pre"> </span>//快速排序的递归实现
if ( (right - left) > Cutoff){
if ( left < right ){
int Pivot = Median(A, left, right);
int i = left;
int j = right - 1;
for ( ; ; ){
while ( A[++i] < A[Pivot] ){}
while ( A[--j] > A[Pivot] ){}
if ( i < j )
swap( &A[i] , &A[j] );
else break;
}
swap( &A[i] , &A[right - 1] );
Quicksort(A,left,i-1);
Quicksort(A,i+1,right);
}
}
else
InsertionSort(A,left,right);
}
【搬运】浙大 数据结构 快速排序
最新推荐文章于 2022-12-30 16:13:37 发布