//快速排序思想
//选取一个基准值一般选取右值,从前往后遍历找到一个小于基准值的值然后停下来,从后往前找一个大于基准值的值然后停下来
//交换left,right此时,继续向后,向前遍历,直到找到left=right的时候,那么就第一次遍历完成,然后交换基准值与left=right的值
//此时的结果是划分为了两个区间,继续按照上述方法排序,直到每一个小区间只剩下一个值的时候就排序完成。
//时间复杂度O(NLogN) 最坏时间复杂度(O(N^2))
//优化方案 选区基准值为(比较左右中下标的大小,选区中间值)
//—因为如果选区基准值接近数组数据的最大值或者最小值,快速排序最坏情况就发生了
//==================递归实现==快速排序
//交换函数
int PartSort(int arr[], int left, int right)
{
if (right - left <= 1)
return left;
int left_index = left;
int right_index = right;
int basic_value = arr[right - 1];
while (left_index < right_index)
{
while (left_index < right_index&&arr[left_index] < basic_value)
left_index++;
while (left_index<right_index&&arr[right_index]>=basic_value)
right_index--;
Swap(&arr[left_index], &arr[right_index]);
}
Swap(&arr[left_index], &arr[right - 1]);
}
//递归函数
void _QuickSort(int arr[], int left, int right)
{
if (arr == NULL || right - left <= 1)
return;
int mid = PartSort(arr, left, right);
_QuickSort(arr, left, mid);
_QuickSort(arr, mid + 1, right);
}
//主函数
void QuickSort(int arr[], int size)
{
if (arr == NULL || size <= 1)
return;
int left = 0;
int right = size;
_QuickSort(arr, left, right);
}
//=================非递归实现===快速排序
//交换函数
int PartSort(int arr[], int left, int right)
{
if (right - left <= 1)
return left;
int left_index = left;
int right_index = right - 1;
int basic_value = arr[right - 1];
while (left_index < right_index)
{
while (left_index < right_index&&arr[left_index] < basic_value)
left_index++;
while (left_index < right_index&&arr[right_index] >= basic_value)
right_index--;
Swap(&arr[left_index], &arr[right_index]);
}
Swap(&arr[left_index], &arr[right - 1]);
}
//非递归函数
void _QuickSort(int arr[], int left, int right)
{
stack<int>s;
s.push(right);
s.push(left);
while (!s.empty())
{
int begin = s.top(); //划分左区间
s.pop();
int end = s.top(); //划分右区间
s.pop();
int mid = PartSort(arr, begin, end);
if (begin < mid - 1) //模拟递归左区间
{
s.push(mid - 1);
s.push(begin);
}
if (mid + 1 < end) //模拟递归右区间
{
s.push(end);
s.push(mid + 1);
}
}
}
void QuickSort(int arr[], int size)
{
if (arr == NULL || size <= 1)
return;
int left = 0;
int right = size;
_QuickSort(arr, left, right);
return;
}