[数据结构与算法]快速排序的优化实现(取中位数)
#include "iostream"
using namespace std;
int Partion(int array[], int low, int high);
void findMid(int array[], int low, int high);
void QuickSort(int array[], int low, int high)//主函数
{
if (low<high)
{
int pos = Partion(array, low, high);//将数组划分成两份,左边都比pos位置的元素小,右边都比它大,并且返回其枢纽元素的位置
QuickSort(array, low, pos - 1);//递归划分枢纽元素左右两侧的元素
QuickSort(array, pos + 1, high);
}
}
int Partion(int array[],int low,int high) //划分函数
{
findMid(array, low, high);//优化方法,先找出low,high,mid中的中间元素,然后交换到数组开头
int keyVal = array[low];
while (low < high) {//
while (low < high&&keyVal< array[high]) high--;
array[low] = array[high];
while (low<high&&keyVal>array[low]) low++;
array[high] = array[low];
}
array[low] = keyVal;
return low;
}
void findMid(int array[], int low, int high)
{
int lowval = array[low];
int midval = array[(low + high) / 2];
int highval = array[high];
int keyVal;
if (lowval<highval&&lowval>midval || lowval<midval&&lowval>highval)//low是中位数
{
keyVal = lowval;
}
else if (midval > lowval&&midval<highval || midval>highval&&midval < lowval)//mid是中位数
{
keyVal = midval;
int temp = array[low];
array[low] = array[(low + high) / 2];
array[(low + high) / 2] = temp;
}
else//high是中位数
{
keyVal = highval;
int temp = array[low];
array[low] = array[high];
array[high] = temp;
}
}
void main()
{
int array[] = { 10,9, 2, 3 , 6 , 4, 7 ,1 , 5, 11, 8 };
QuickSort(array, 0, sizeof(array)/sizeof(int)-1);
for each (int var in array)
{
cout << var << " ";
}
cout << endl;
}
上面的实现方法也只是优化的方法之一,像STL里的sort排序也采用了:当快速排序最后元素的个数少于一定数量的时候,改为直接插入排序(直接插入排序在元素个数较少的时候性能较优)。
https://github.com/li-zheng-hao