algo. quick_sort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.*;

public class Main {
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] + " ");
}
}

public static void quick_sort(int[] q, int l, int r) {
if (l >= r) return;

int pivot = q[l + r >> 1];
int i = l - 1, j = r + 1;

while (i < j) {
do i++; while (q[i] < pivot);
do j--; while (q[j] > pivot);
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);
}
}

algo. quick_sort
http://elwinliu.com/2024/09/08/algo. quick_sort/
Author
Elwin
Posted on
September 8, 2024
Licensed under