题解 | #排序#
排序
http://www.nowcoder.com/practice/2baf799ea0594abd974d37139de27896
public int[] MySort (int[] arr) {
// write code here
int len = arr.length;
quickSort(arr,0,len-1);
return arr;
}
private void quickSort(int[] nums,int left,int right){
if(left>=right){
return;
}
int pivot = nums[left];
//循环不变量
//[left,low)<pivot
//[low,i)=pivot
//[high,right]>pivot
int low = left;
int high = right+1;
int i = left;
while(i<high){
if(nums[i]<pivot){
low++;
swap(nums,i,low);
i++;
}else if(nums[i] == pivot){
i++;
}else{
high--;
swap(nums,i,high);
}
}
swap(nums,left,low);
quickSort(nums,left,low-1);
quickSort(nums,low+1,right);
}
private void swap(int[] nums,int i,int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
// write code here
int len = arr.length;
quickSort(arr,0,len-1);
return arr;
}
private void quickSort(int[] nums,int left,int right){
if(left>=right){
return;
}
int pivot = nums[left];
//循环不变量
//[left,low)<pivot
//[low,i)=pivot
//[high,right]>pivot
int low = left;
int high = right+1;
int i = left;
while(i<high){
if(nums[i]<pivot){
low++;
swap(nums,i,low);
i++;
}else if(nums[i] == pivot){
i++;
}else{
high--;
swap(nums,i,high);
}
}
swap(nums,left,low);
quickSort(nums,left,low-1);
quickSort(nums,low+1,right);
}
private void swap(int[] nums,int i,int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}