快速排序

快速排序分成以下两步:

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值