c++实现快速排序

主体结构

void quicksort(int low, int high) {
  if(low < high) {
    int mid = partition(low, high);
    quicksort(low, mid-1);
    quicksort(mid+1, high);    
  }
}

将数组中的段再处理成: 左半边的数比pivot小,右半边的数比pivot大
处理到一半的效果是: last_small左边的数小于等于pivot, last_small到i之间的数比pivot大, i后的数未知.
遍历完成后, 将last_smalll所在的值与pivot替换就得到了需要的结果

int partition(int low, int high) {
  int mid = (high+low)/2;
  int last_small = low, pivot = array[mid];
  m_swap(low, mid);
  for(int i = low+1; i <= high; i++)
    if(array[i] < pivot) {
      last_small++;       //如果发现比pivot小的数, 将它加入到last_samll左边的那一段
      m_swap(last_small, i);
    }
  m_swap(low, last_small);
  return last_small;
}

swap函数

void m_swap(int a, int b) {
  int tmp = array[a];
  array[a] = array[b];
  array[b] = tmp;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值