快速排序
import java.util.*;
class Main{
private static void quick_sort(int[] q, int l, int r){
if(l >= r) return; //回退 左右交点
int i = l - 1, j = r + 1, x = q[l + r >> 1];
while(i < j){ // 左 小于 右
// 左右两部分组成,并且右边部分的数字都大于等于左边数组中的数字
do i ++; while(q[i] < x);
do j --; while(q[j] > x);
if(i < j){
int temp = q[i];
q[i] = q[j];
q[j] = temp;
}
}
quick_sort(q, l, j);
quick_sort(q, j + 1, r);
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] q = new int[n];
for(int i = 0; i < n; i ++){
q[i] = sc.nextInt();
}
quick_sort(q, 0, n - 1);
for(int i = 0; i < n; i ++){
System.out.print(q[i] + " ");
}
}
}
第k个数
给定一个长度为 n 的整数数列,以及一个整数 k ,请用快速选择算法求出数列从小到大排序后的第 k 个数。
5 3 2 4 1 5 3
3
import java.util.*;
class Main{
public static void qucik_sort(int[] q, int l, int r){
if(l >= r) return;
int i = l - 1,j = r + 1, x = q[l + r >> 1];
while(i < j){
do i ++; while(q[i] < x);
do j --; while(q[j] > x);
if(i < j){
int temp = q[i];
q[i] = q[j];
q[j] = temp;
}
}
qucik_sort(q,l,j);
qucik_sort(q,j + 1,r);
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int index = sc.nextInt();
int[] num = new int[n];
for(int i = 0; i < n; i++){
num[i] = sc.nextInt();
}
qucik_sort(num,0,n-1);
System.out.print(num[index- 1]);
}
}
自定义排序
class Solution {
public int[] relativeSortArray(int[] arr1, int[] arr2) {
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < arr2.length; i ++){
map.put(arr2[i],i);
}
//通过boxed()方法将int类型的元素转化为Integer类型,因为流中的元素需要是可变的。
return Arrays.stream(arr1).boxed().sorted((i1,i2) -> {
//如果map中同时包含i1和i2作为键(key),那么根据map.get(i1)和map.get(i2)返回的值进行比较
if(map.containsKey(i1) && map.containsKey(i2)){
return map.get(i1) - map.get(i2);
//如果map中只包含i1作为键,那么返回-1,这意味着i1应该在排序后的序列中出现在i2之前
}else if(map.containsKey(i1)){
return -1;
//如果map中只包含i2作为键,那么返回1,这意味着i1应该在排序后的序列中出现在i2之后
}else if(map.containsKey(i2)){
return 1;
}else {
//如果map中不包含i1和i2作为键,那么直接返回i1 - i2的结果,这意味着根据元素本身的自然顺序进行比较
return i1 - i2;
}
}).mapToInt(Integer::valueOf).toArray();
}
}
https://leetcode.cn/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/description/
输入:nums = [1,2,3,4]
输出:[1,3,2,4]
注:[3,1,2,4] 也是正确的答案之一。
class Solution {
public int[] exchange(int[] nums) {
int n = nums.length;
int[] res = new int[n];
int left = 0, right = n - 1;
for (int num : nums) {
if (num % 2 == 1) {
res[left++] = num;
} else {
res[right--] = num;
}
}
return res;
}
}