快速排序分成以下两步:
1.把基准数大的都放在基准数的右边,把比基准数小的放在基准数的左边,这样就找到了该数据在数组中的正确位置.
①先从队尾开始向前扫描且当low < high时,如果arr[high] > 基准数,则high–,但如果arr[high] < 基准数,则将high的值赋值给low,即arr[low] = a[high],同时要转换数组扫描的方式,即需要从队首开始向队尾进行扫描了
②同理,当从队首开始向队尾进行扫描时,如果arr[low] < 基准数,则low++,但如果arr[low] > 基准数了,则就需要将low位置的值赋值给high位置,即arr[low] = arr[high],同时将数组扫描方式换为由队尾向队首进行扫描.
③不断重复①和②,知道low>=high时(其实是low=high),low或high的位置就是该基准数据在数组中的正确索引位置.
2.采用递归的方式分别对前半部分和后半部分排序,当前半部分和后半部分均有序时该数组就自然有序了
#include "iostream"
#include "vector"
using namespace std;
int GetIndex(std::vector<int> &temp_array, int low, int high) {
int temp_single = temp_array.at(low);
while(low < high) {
while(low < high && temp_array.at(high) >= temp_single) {
high--;
}
temp_array.at(low) = temp_array.at(high);
while(low < high && temp_array.at(low) <= temp_single) {
low++;
}
temp_array.at(high) = temp_array.at(low);
}
temp_array.at(low) = temp_single;
return low;
}
int QuickSort(std::vector<int> &temp_array, int low, int high) {
if (low < high) {
int index = GetIndex(temp_array, low, high);
QuickSort(temp_array, low, index - 1);
QuickSort(temp_array, index + 1, high);
}
return 0;
}
int main(void) {
std::vector<int> temp_array = {1,5,2,9,6,4,7,0,8,3};
QuickSort(temp_array, 0, temp_array.size() - 1);
for (const auto &temp : temp_array) {
std::cout << "temp " << temp << std::endl;
}
return 0;
}