c++实现快速排序

来源:互联网 发布:linux怎么创建用户密码 编辑:程序博客网 时间:2024/05/16 17:34

主体结构

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