一、快速排序
快速排序,面试经常可能碰到的题,今天整理了一下,方便以后自己查看复习。原理可以参见博客:快速排序的原理
我也是参考这个博客的,写的挺好的。以下是c++代码。
#include<bits/stdc++.h>
using namespace std;
//找到基准数下标
int getIndex(vector<int>& arr, int low, int high) {
int temp = arr[low];
while (low < high) {
while (arr[high] >= temp && high > low)
high--;
arr[low] = arr[high];
while (arr[low] <= temp && high > low)
low++;
arr[high] = arr[low];
}
arr[low] = temp;
return low;
}
void quickSort(vector<int>& arr, int low, int high) {
if (low < high) {
int index = getIndex(arr, low, high);
quickSort(arr, low, index - 1);
quickSort(arr, index + 1, high);
}
}
//主函数测试一下
int main() {
vector<int> arr = {
2,