码迷,mamicode.com
首页 > 其他好文 > 详细

Quick Sort

时间:2018-02-15 10:31:10      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:stack   ret   oid   loop   note   public   write   point   return   

 1 public class QuickSort {
 2 
 3     private static int listToSort[] = new int[] {3,2,1,4,5};
 4 
 5     public void sortIntegers(int[] A) {
 6         // write your code here
 7         if (A == null || A.length ==0 ) {
 8             return ;
 9         }
10         quickSort(A, 0, A.length-1);
11     }
12     //the partition
13     private void quickSort(int[] A, int start, int end) {
14         if (start>=end ) {
15             return;
16         }
17         int left = start, right = end;
18         //note 1: find the middle one as the pivot: dont use the start or the end. get the value not index
19         int pivot = A[(start+end)/2] ;
20         //partition phase
21         /*note 2: left<=right
22         * if you change tot left < right, will generate stack over flow issue
23         *
24         * */
25         while (left<=right) {
26             //===找到  A[left] >= PIVOT 和  A[right] <= pivot 的 LEFT 和 RIGHT
27             //为了平衡性(更好的找PIVOT), A[left]< pivot A[right] > pivot
28             /*如果 LEFT<RIGHT
29                part 1: sorting
30              * [1  2] pivot value = 1
31              *  L/R  both point to 1
32              *  quickSort(A, start, right);  [1,1] this is ok, will exit @ when start>=end
33                 quickSort(A, left, end);     [1,2]  so this will cause stack over flow
34                 part 2: sorting: note we have overlap of the item [2]
35                 [2,3,4,5]
36               if use left <= right, continue the while loop, pivot value still = 1
37               right[1]
38               left [2,3,4,5]
39              * */
40             while (left<=right && A[left]< pivot) {
41                 left++;
42             }
43             while (left<=right && A[right] > pivot) {
44                 right--;
45             }
46             //找到left>= pivot && right <= pivot‘s 的 LEFT 和 RIGHT 的值. swap left right 指针的值
47             if (left<=right) {
48                 int temp = A[left];
49                 A[left] = A[right];
50                 A[right] = temp;
51                 left++;
52                 right--;
53             }
54         }
55         //当不在WHILE 循环中的时候,说明 LEFT > RIGHT
56         quickSort(A, start, right);
57         quickSort(A, left, end);
58     }
59 }

 

Quick Sort

标签:stack   ret   oid   loop   note   public   write   point   return   

原文地址:https://www.cnblogs.com/davidnyc/p/8449202.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!