快排思想:
快速排序就是取一个数将所有数据分割两部分,前一部分数字比取的数字小,后一部分数字都比取的这个数字大。这样的情况下,就能确定取的这个数就在这个位子。然后在通过分治思想,把两部分数据接着使用快速排序,递归的思想把所有数据能排好序。
优化策略:
1.三点取中
就是三个数取到第二大的,如果快排的话每一趟取到整个数的越中间越好。
2.少数量数字,用插入排序
3.聚集优化
遇到像年龄这种,大量数据时候,可能会出现大量数据等于一个数。利用Gather函数
快排实现:
//优化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");
}