阅读447 返回首页    go 阿里云 go 技术社区[云栖]


快速排序

49 38 65 97 76 13 27——————49原始

27 38 65 97 76 13 49——————49   1

27 38 49 97 76 13 65——————49   2

27 38 13 97 76 49 65——————49   3

27 38 13 49 76 97 65——————49   4

一趟快速排序

 

排序1:

#include <iostream> #include <time.h> #define ARYSIZE 100000 using namespace std; void QuickSort(int ary[], int nBegin, int nEnd) { int tKey = ary[nBegin]; int tLeft = nBegin; int tRight = nEnd;//以第一个数为参照做比较 if(tLeft >= tRight) { return; } while(tLeft < tRight) { while(tLeft < tRight && ary[tRight] >= tKey) { tRight--; } ary[tLeft] = ary[tRight]; while(tLeft < tRight && ary[tLeft] <= tKey) { tLeft++; } ary[tRight] = ary[tLeft]; } ary[tRight] = tKey; QuickSort(ary, nBegin, tRight-1); QuickSort(ary, tRight+1, nEnd);//递归 } int main(int argc, char *argv[]) { int ary[ARYSIZE] = {0}; srand((unsigned int)time(NULL)); for (int i = 0; i < ARYSIZE; ++i) { ary[i] = rand() % 100; } QuickSort(ary, 0, ARYSIZE - 1); getchar(); }

排序1比较块;

 

排序2:

#include <iostream> #include <time.h> #define ARYSIZE 100000 using namespace std; void swap(int *a, int *b) { int t=*a; *a=*b; *b=t; } void QuickSort(int arr[], int beg, int end) { if (end >= beg + 1) { int piv = arr[beg], k = beg + 1, r = end; while (k < r) { if (arr[k] < piv) { k++; } else { swap(&arr[k], &arr[r--]); } } if (arr[k] < piv) { swap(&arr[k],&arr[beg]); QuickSort(arr, beg, k); QuickSort(arr, r, end); } else { if (end - beg == 1) { return; } swap(&arr[--k],&arr[beg]); QuickSort(arr, beg, k); QuickSort(arr, r, end); } } } int main(int argc, char *argv[]) { int ary[ARYSIZE] = {0}; srand((unsigned int)time(NULL)); for (int i = 0; i < ARYSIZE; ++i) { ary[i] = rand() % 100; } QuickSort(ary, 0, ARYSIZE - 1); getchar(); }

最后更新:2017-04-02 06:51:35

  上一篇:go magento -- 按某个属性排序上的一个尝试
  下一篇:go QML使MeeGo迅速崛起赶超Android变为可能