1、题目描述
给你一个整数数组 nums
,请你将该数组升序排列。
2、算法分析
方法一:快速排序
最最重要的是选择一个基准数,通过一趟快排将数据分割成两部分,基准值左边的部分是小于基准值的,基准值右边的部分是大于基准值的。然后再分别对两部分的数据进行排序,可以递归执行。
3、代码实现
// 快排
class Solution {
public int[] sortArray(int[] nums) {
if(nums == null || nums.length == 0){
return null;
}
sort(nums,0,nums.length - 1);
return nums;
}
public void sort(int[] nums,int left,int right){
if(left < right){
// 获取基准值
int index = getIndex(nums,left,right);
// 基准值左边进行排序
sort(nums,left,index - 1);
// 基准值右边进行排序
sort(nums,index + 1,right);
}
}
// 获取基准值的位置
public int getIndex(int[] nums,int left,int right){
// 初始化基准值
int temp = nums[left];
while(left < right){
//从右往左找比基准值小的元素,否则就往左移动,right--
while(left < right && nums[right] >= temp){
right--;
}
// 比基准值小的元素,元素左移动
nums[left] = nums[right];
//从左往右找到比基准值大的元素,找不到就右移动
while(left < right && nums[left] <= temp){
left++;
}
nums[right] = nums[left];
}
// 将基准值赋值到该位置
nums[left] = temp;
// 获取基准值的位置
return left;
}
}