1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| public int[] sortArray(int[] nums){ int len = nums.length; quickSort(nums,0,len-1); return nums; }
private void quickSort(int[] nums,int start,int end){ if(start >= end) return; int index = partition(nums,start,end); quickSort(nums,start,index-1); quickSort(nums,index+1,end); }
private int partition(int[] nums, int start, int end) { int random = new Random().nextInt(end - start + 1) + start; swap(nums,start,random);
int pivot = nums[start]; int left = start+1,right = end; while(true){ while (left <= end && nums[left] <= pivot) left++; while (start <= right && nums[right] > pivot) right--; if(left >= right) break; swap(nums,left,right); left++; right--; } nums[start] = nums[right]; nums[right] = pivot; return right; }
private void swap(int[] nums, int index1, int index2) { int temp = nums[index1]; nums[index1] = nums[index2]; nums[index2] = temp; }
|