快速排序

 1 int Partition(int r[] , int low ,int high){
 2     pivot = r[low];
 3     while(low < high){
 4         while(low < high && r[high] >= pivot) --highl;
 5       
 6             int temp = r[high];
 7             r[high] = r[low];          //优化方法:r[low] = r[high];
 8             r[low] = temp;
 9         
10         while(low < high && r[low] <= pivot) ++low;
11         
12              int temp = r[high];
13             r[high] = r[low];          //优化方法:r[high]=r[low];
14             r[low] = temp;
15         
16     }
17              //优化方法:r[low]=pivot;
18     return low;
19 }
20 void QuickSort(int r[] , int low , int high){
21     if(low < high){
22         pivot = Partition(r , low , high);
23         QuickSort(r , low , pivot - 1);
24         QuickSort(r , pivot +1 , high);
25     }
26 }

6、快速排序(Quick Sort)

快速排序的基本思想:通过一趟排序将待排记录分隔成独立的两部分,其中一部分记录的关键字均比另一部分的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序。

6.1 算法描述

快速排序使用分治法来把一个串(list)分为两个子串(sub-lists)。具体算法描述如下:

  • 从数列中挑出一个元素,称为 “基准”(pivot);
  • 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。在这个分区退出之后,该基准就处于数列的中间位置。这个称为分区(partition)操作;
  • 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序。

6.2 动图演示

posted @ 2019-04-29 21:48  unique_ptr  阅读(115)  评论(0编辑  收藏  举报