# 快速排序

1.三点取中

2.少数量数字，用插入排序

3.聚集优化

//优化1：最坏情况  随机取基准点
//优化2：三分取中  从数组中三个标志位取中间大的值左基准值
//low  mid  high
//普通情况：给出的数据本身随机

//优化3：小数据量  插排
//优化4：聚集优化
//重复数据
//优化5：递归写成非递归  ==>
void Swap(int[], int, int);
void Gather(int arr[], int low,
int broundKey, int high,
int *left, int * right)
{
int count = broundKey - 1;
for (int i = broundKey - 1; i >= low; --i)
{
if (arr[i] == arr[broundKey])
{
Swap(arr, count, i);
count--;
}
}
*right = count;
count = broundKey + 1;
for (int i = broundKey + 1; i <= high; ++i)
{
if (arr[i] == arr[broundKey])
{
Swap(arr, count, i);
count++;
}
}
*left = count;
}
//void InsertSort(int arr[], int low, int high);
void FindMiddleNumber(int arr[], int low, int mid, int high)
{
if (arr[mid] > arr[high])
{
Swap(arr, mid, high);
}
if (arr[low] < arr[mid])
{
Swap(arr, low, mid);
}
if (arr[low] > arr[high])
{
Swap(arr, low, high);
}
}
void Swap(int arr[], int first, int second)
{
int tmp = arr[first];
arr[first] = arr[second];
arr[second] = tmp;
}

int Parition(int arr[], int low, int high)   //快速排序的核心思想
{
int tmp = arr[low];
while (low < high)
{
while (low < high && arr[high] >= tmp)high--;
arr[low] = arr[high];
while (low < high && arr[low] <= tmp)low++;
arr[high] = arr[low];
}
arr[low] = tmp;
return low;
}
void QSort(int arr[], int low, int high)
{
if (low < high)
{
/*	if (high - low < 20)
{
InsertSort(arr, low, high);
return;
} */

//Swap(arr, low, rand() % (high - low) + low);
FindMiddleNumber(arr, low, (high - low) / 2 + low, high);

int broundKey = Parition(arr, low, high);
int left = broundKey + 1;
int right = broundKey - 1;
Gather(arr, low, broundKey, high, &left, &right);
//QSort(arr, low, broundKey - 1);
//QSort(arr, broundKey + 1, high);
QSort(arr, low, right);
QSort(arr, left, high);
}
}
void QuickSort(int arr[], int len)
{
QSort(arr, 0, len - 1);
}
void QuickShow(int arr[], int len)
{
for (int i = 0; i < len; ++i)
{
printf("%d ", arr[i]);
}
printf("\n");
}

05-03 253

03-13 2627
11-29 15万+
08-13 63万+
09-10 44万+
01-29 6万+
07-02 25万+
06-12 10万+
03-05 6万+
02-07 400
11-04 11万+
12-25 3440
09-12 2020
07-01 4万+
10-08 2万+
02-22 75
03-13 14万+
04-24 1万+