public class QuickSort {
public void sort(int[] nums){
sort(nums,0,nums.length-1);
}
private void sort(int[] nums,int left,int right){
if(left>=right)
return;
int _left = left,_right = right;
int pivot = left;
while(true){
//一定要right先走,为了在与left相遇时,处于比pivot小的情况
while(nums[right]>=nums[pivot]&&left<right)
right--;
while(nums[left]<=nums[pivot]&&left<right)
left++;
if(left<right){//普通步骤
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}else{//left与right相遇,将原left与当前值交换
int temp = nums[pivot];
nums[pivot] = nums[right];
nums[right] = temp;
break;
}
}
sort(nums, _left, left-1);
sort(nums, left+1, _right);
}
public void quickSort(int[] nums) {
quickSort(nums, 0, nums.length - 1);
}
private void quickSort(int[] nums, int left, int right) {
if (left < right) {
int pivotNum = nums[left];
int _left = left;
int _right = right;
while (left < right) {
while (left < right && nums[right] >= pivotNum)
right--;
nums[left] = nums[right];
while (left < right && nums[left] <= pivotNum)
left++;
nums[right] = nums[left];
}
nums[left] = pivotNum;
quickSort(nums, _left, left - 1);
quickSort(nums, left + 1, _right);
}
}
}