AcWing 785. 快速排序
原题链接
简单
作者:
Lumos_18
,
2024-03-04 23:51:00
,
所有人可见
,
阅读 15
快排(JAVA)
//BufferRead(要注意空格输入,可先存为一个字符串数组)读取速度比Scanner快,但是这题都不超时、
//注意边界问题,递归中取j则中间值不能用同一侧的边界的q[r]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
private static void quick_sort(int[] q, int l, int r) {
if (l >= r)
return;
int x = q[l+r>>1], i = l - 1, j = r + 1;
while (i < j) {
do {
i++;
} while (q[i] < x);
do {
j--;
} while (q[j] > x);
if (i < j) {
int t = q[i];
q[i] = q[j];
q[j] = t;
}
}
quick_sort(q, l, j);
quick_sort(q, j + 1, r);
}
public static void main(String[] args) throws IOException{
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
String line = buffer.readLine();
if (line == null || line.isEmpty()) {
buffer.close();
return;
}
int n = Integer.parseInt(line);
int[] q = new int[n];
String[] str = buffer.readLine().split(" ");
for (int i = 0; i < n; i++) {
q[i] = Integer.parseInt(str[i]);
}
quick_sort(q, 0, n - 1);
for (int i = 0; i < n; i++) {
System.out.print(q[i] + " ");
}
buffer.close();
}
}