forked from dangger/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
57 lines (46 loc) · 1.28 KB
/
Copy pathQuickSort.java
File metadata and controls
57 lines (46 loc) · 1.28 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
* Input:8 9 1 2 4 8 6 15 8
* Output:1 2 4 6 8 8 9 15
* */
import java.util.Scanner;
public class QuickSort {
public static void quickSort(int[] num, int left, int right) {
if (left < right) {
int x = Partition(num, left, right);
quickSort(num, left, x - 1);
quickSort(num, x + 1, right);
}
}
public static int Partition(int[] num, int left, int right) {
int i = left, j = right + 1;
int x = num[left];
while (true) {
while (num[++i] < x && i < right) ;
while (num[--j] > x) ;
if (i >= j) break;
swap(num, i, j);
}
num[left] = num[j];
num[j] = x;
return j;
}
public static void swap(int[] num, int a, int b) {
int t = num[a];
num[a] = num[b];
num[b] = t;
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int[] num = new int[100];
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
num[i] = sc.nextInt();
}
quickSort(num, 0, n - 1);
System.out.print(num[0]);
for (int i = 1; i < n; i++) {
System.out.print(" " + num[i]);
}
System.out.println();
}
}