//快速排序实现方法一
void quick_sort(int s[],int l,int r)//先去第一个元素作为基准,从后面比较 { int i = l, j = r, base = s[i];//挖坑 while (i<j&&s[j]>base) { j--; } if (i<j) { s[i++] = s[j];//填数 } while (i<j&&s[i]<base) { i++; } if (i<j) { s[j++] = s[i]; } s[i] = base; quick_sort(s,l,i-1); quick_sort(s, i + 1, r); }
//实现方法二 //以最后一个作基准,从左到右走
int patition(int gArr[], int begin, int end){ int index, small; small = begin - 1; for (index = begin; index < end; index++){ //最后一个作为基准,从头开始比较 if (gArr[index] < gArr[end]){ small++; if (small != index) //如果有不等于时,即index和small交换 swap(index, small); } } small++; swap(small, end); return small; } void swap(int gArr[],int i, int j){ int tmp = gArr[j]; gArr[j] = gArr[i]; gArr[i] = tmp; }
理解选择标准在头还是尾!
好理解的: //两边往中间走
void qsort(int *array, int len) { int value, start, end; if (len <= 1) return; value = array[0]; start = 0; end = len - 1; while (start < end) { for (; start < end; --end) { if (array[end] < value) { array[start++] = array[end]; break; } } for (; start < end; ++start) { if (array[start] > value) { array[end--] = array[start]; break; } } } array[start] = value; qsort(array, start); qsort(array+start+1, len-start-1); }
#ifndef QUICK_SORT_HPP #define QUICK_SORT_HPP template <typename T> void Swap(T & a, T &b) { T temp = a; a = b; b = temp; } /*快速排序*/ template <typename T> int Partition(T arr[], int start, int end) { T x = arr[start]; //保存基准的值,这里并没有使用随机基准 int i = start; int j = start + 1; while (j <end) { if (arr[j] >=x) { i = i+1; Swap(arr[i], arr[j]); } j++; } Swap(arr[i], arr[start]); return i; } template <typename T> void QuickSort(T arr[], int start, int end) { if (start < end) { int i = Partition(arr, start, end); QuickSort(arr, start, i ); QuickSort(arr, i + 1, end); } } template <typename T> void QuickSort(T arr[], int length) { QuickSort(arr, 0, length); } #endif