-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
59 lines (47 loc) · 1.49 KB
/
QuickSort.java
File metadata and controls
59 lines (47 loc) · 1.49 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
58
59
package com.pslin.algorithms.sort;
import java.util.Arrays;
/**
* @author plin
*/
public class QuickSort {
public static void main(String[] args) {
int length;
if(args.length == 0 ) {
length = 10000;
} else {
length = Integer.parseInt(args[0]);
}
int[] numbers = ArrayUtils.createArray(length);
ArrayUtils.shuffle(numbers);
System.out.println(Arrays.toString(numbers));
long start = System.currentTimeMillis();
quicksort(numbers, 0, numbers.length - 1);
long totalTime = System.currentTimeMillis() - start;
System.out.println(Arrays.toString(numbers));
System.out.println("Time: " + totalTime + " ms");
}
private static void quicksort(int[] numbers, int pivot, int range) {
if (pivot < range) {
int q = partition(numbers, pivot, range);
quicksort(numbers, pivot, q);
quicksort(numbers, q + 1, range);
}
}
private static int partition(int[] a, int pivot, int range) {
int x = a[pivot];
int i = pivot - 1;
int j = range + 1;
while (true) {
i++;
while (i < range && a[i] < x)
i++;
j--;
while (j > pivot && a[j] > x)
j--;
if (i < j)
ArrayUtils.swap(a, i, j);
else
return j;
}
}
}