首页 > 代码库 > 最優化的快排,減少不必要的交換

最優化的快排,減少不必要的交換

只有當左邊的指大於pivot,右邊的值小於pivot才交換
 
 1 public static quickSortOptimized(int[] data,int left,int right){ 2  3 int pivotIndex=(left+right)/2; 4 int pivotValue=http://www.mamicode.com/data[pivotIndex]; 5 int i=left; 6 int j=right; 7  8 while(i<=j){ 9 10 //find left value greater than or equal to the pivotValue11 12 if(data[i]<pivotValue) i++;13 14 //find right value smaller than or equal to the pivotValue15 if(data[j]>pivotVaule) j++;16 17 //swapping the values in wrong places18 if(i<=j){19 20 swap(data,i,j);21 i++;22 j--;23 24 25 26 }27 28 29 30 }31 32 33 //recursive34 35 if(left<j){36 quickSortOptimized(data,left,j);37 }38 39 if(right>i){40 41 quickSortOptimized(data,i,right);42 }43 }

 

最優化的快排,減少不必要的交換