题目:给你一个整数数组 nums,请你将该数组升序排列。
详细要求见LeetCode912
方法一:快速排序
快速排序原理:
1.选定中心轴数
2.将比中心轴数小的数放在中心轴的左边,构成左子数组,比中心轴大的数放在中心轴右边,构成右子数组
3.左子数组、右子数组重复上述操作
class Solution {
public int[] sortArray(int[] nums) {
QuickSort(nums,0,nums.length-1);
return nums;
}
public void QuickSort(int[] nums,int start,int end){
int index=Partition(nums,start,end);//获得中心轴数下标
if(start==end)
return;
if(start<index){
QuickSort(nums,start,index-1);//对左子数组排序
}
if(index<end){
QuickSort(nums,index+1,end);//对右子数组排序
}
}
public int Partition(int[] nums,int start,int end){
int index=(int)(Math.random()*(end-start+1)+start);//随机确定中心轴
swap(nums,index,end);//将中心轴数移到最后
int small=start-1;
for(index=start;index<end;index++){
if(nums[index]<=nums[end]){
small++;
if(small!=index)
swap(nums,index,small);
}
}
small++;
swap(nums,small,end);//将中心轴数插入到左子数组后
return small;
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
说明:
Partition函数返回左子数组后的第一个数的下标,即中心轴数的下标
java 中不能直接使用swap交换函数,因为java只有值传递,故重写swap方法,通过传数组的方法实现。