只有當左邊的指大於pivot,右邊的值小於pivot才交換
1 public static quickSortOptimized(int[] data,int left,int right){ 2 3 int pivotIndex=(left+right)/2; 4 int pivotValue=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 pivotValue 11 12 if(data[i]<pivotValue) i++; 13 14 //find right value smaller than or equal to the pivotValue 15 if(data[j]>pivotVaule) j++; 16 17 //swapping the values in wrong places 18 if(i<=j){ 19 20 swap(data,i,j); 21 i++; 22 j--; 23 24 25 26 } 27 28 29 30 } 31 32 33 //recursive 34 35 if(left<j){ 36 quickSortOptimized(data,left,j); 37 } 38 39 if(right>i){ 40 41 quickSortOptimized(data,i,right); 42 } 43 }
时间: 2024-08-27 02:17:36