手写堆排序:https://blog.csdn.net/weixin_42887343/article/details/119930432
1 快速排序的原理
2 快速排序函数
int getIndex(vector<double>& arr, int low, int high)
{
double tmp = arr[low]; // 首个元素作为基准数据
while (low < high)
{
while (low < high && arr[high] >= tmp) high --; // 当队尾的元素大于等于基准数据时,向前挪动high指针
arr[low] = arr[high]; // 如果队尾元素小于tmp了,需要将其赋值给low
while (low < high && arr[low] <= tmp) low ++; // 当队首元素小于等于tmp时,向前挪动low指针
arr[high] = arr[low]; // 当队首元素大于tmp时,需要将其赋值给high
}// 跳出循环时low和high相等,此时的low或high就是tmp的正确索引位置
//由原理部分可以很清楚的知道low位置的值并不是tmp,所以需要将tmp赋值给arr[low]
arr[low] = tmp;
return low; // 返回tmp的正确位置
}
void quickSort(vector<double>& arr, int low, int high)
{
if (low < high)
{
int index = getIndex(arr, low, high); // 找寻基准数据的正确索引
quickSort(arr, low, index - 1); //左边递归
quickSort(arr, index + 1, high); //右边递归
}
}
上面排序对象是vector,如果需要排序int数组或者其他数组,只需要换几个地方便可解决。
- int getIndex(vector& arr, int low, int high) 改为 int getIndex(int arr[], int low, int high)
- double tmp = arr[low]; 改为 int tmp = arr[low];
- void quickSort(vector& arr, int low, int high) 改为 void quickSort(int arr[], int low, int high)
3 demo代码(leetcode中的考试题)
double getAdmissionLine(int k, vector<double>& scores)
{
quickSort(scores,0,scores.size()-1); //快速排序
if(k > scores.size())
k = 0;
else
k = scores.size()-k;
return scores[k];
}