给你一个整数数组 nums,请你将该数组升序排列。
示例 1:
输入:nums = [5,2,3,1]
输出:[1,2,3,5]
示例 2:
输入:nums = [5,1,1,2,0,0]
输出:[0,0,1,1,2,5]
import java.util.*;
public class Main {
public static void main(String[] args) {
//测试数据
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
arr = sortArray(arr);
System.out.println(Arrays.toString(arr));
}
public static int[] sortArray(int[] nums) {
quickSort(nums,0,nums.length-1);
return nums;
}
public static void quickSort(int[] a, int p, int r){
if(p < r){
int q = partition( a, p , r);
quickSort( a, p, q-1);
quickSort( a, q+1, r);
}
}
public static int partition(int[] a, int p, int r){
int midIndex = p + ((r-p) >> 1);//获得中间索引
int mid = 0;
//三点中值法
if (a[p] >= a[midIndex] && a[p] < a[r]) {
mid = p;
} else if(a[r] >= a[midIndex] && a[r] < a[p]){
mid = r;
} else{
mid = midIndex;
}
swap( a, mid, p);//交换
int temp = a[p];
int up = p;
int later = r;
while ( up <= later){
//获取从up开始的第一个大于temp
while (up <= later && temp >= a[up]) up++;
//获取later前面的第一个小于temp
while ( up <= later && temp < a[later]) later--;
if (up < later) swap( a, up, later);//交换
}
swap( a, p, later);
return later;
}
//交换
public static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
来源:力扣(LeetCode)
题目链接: https://leetcode-cn.com/problems/sort-an-array/