c++之快速排序改进(随机值)
- 数量少(5~25),插入排序很高效
- 一个影响快排效率的因素就是: 基准值的选择
- 本文将演示一种随之法的快排
改进前
void quick_sort5(int arr[], int low, int high)
{
if (0 > low || 0 > high)
return;
if (low > high)
return;
int left = low;
int right = high;
int key = arr[low];
while (left < right)
{
while (left < right && arr[right] >= key)
--right;
if (left < right)
arr[left++] = arr[right];
while (left < right && arr[left] < key)
++left;
if (left < right)
arr[right--] = arr[left];
}
arr[left] = key;
quick_sort5(arr, low, left - 1);
quick_sort5(arr, left + 1, high);
}
改进后
template <typename T>
void quick_sort(T arr[], int low, int high)
{
if (0 > low || 0 > high)
return;
if (low > high)
return;
int left = low;
int right = high;
srand((unsigned) time(NULL));
int pivot_pos = (rand() % (high - low + 1)) + low;
int key = arr[pivot_pos];
while (left < right)
{
while (left < right && arr[right] >= key)
--right;
if (left < right)
arr[left++] = arr[right];
while (left < right && arr[left] < key)
++left;
if (left < right)
arr[right--] = arr[left];
}
arr[left] = key;
quick_sort(arr, low, left - 1);
quick_sort(arr, left + 1, high);
}
核心源码
srand((unsigned) time(NULL));
int pivot_pos = (rand() % (high - low + 1)) + low;
int key = arr[pivot_pos];
改为生成随机数的方法来获取基准数的索引。
缺点
很明显,随机值可能是 0 or max_pos,时间复杂度与改进前是一致的。