publicclassSortArray{publicint[]sortArray(int[] nums){quickSort(nums,0, nums.length -1);return nums;}publicvoidquickSort(int[] nums,int left,int right){if(left < right){int index =partition(nums, left, right);quickSort(nums, left, index -1);quickSort(nums, index +1, right);}}publicintpartition(int[] nums,int l,int r){int k =newRandom().nextInt(r - l +1)+ l;swap(nums, k, r);int pivot = nums[r];while(l < r){while(l < r && nums[l]<= pivot) l++;
nums[r]= nums[l];while(l < r && nums[r]> pivot) r--;//注意这里是r--
nums[l]= nums[r];}
nums[r]= pivot;return r;}privatevoidswap(int[] nums,int i,int j){int tmp = nums[i];
nums[i]= nums[j];
nums[j]= tmp;}}
堆排序
packagecom.mk.www;publicclassHeapSort{publicint[]SortArray(int[] nums){heapSort(nums);return nums;}publicvoidheapSort(int[] nums){int n = nums.length;buildMaxHeap(nums, n);for(int i = n -1; i >=1;--i){swap(nums,0, i);
n--;adjustHeap(nums,0, n);}}publicvoidbuildMaxHeap(int[] nums,int len){for(int i = len /2; i >=0;--i){adjustHeap(nums, i, len);}}publicvoidadjustHeap(int[] nums,int root,int len){for(;(root <<1)+1< len;){int l =(root <<1)+1;int r =(root <<1)+2;int large = root;if(nums[l]> nums[large]) large = l;if(r < len && nums[r]> nums[large]) large = r;if(large != root){swap(nums, large, root);
root = large;}else{break;}}}publicvoidswap(int[] nums,int i,int j){int tmp = nums[i];
nums[i]= nums[j];
nums[j]= tmp;}}