-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
43 lines (31 loc) · 1002 Bytes
/
QuickSort.java
File metadata and controls
43 lines (31 loc) · 1002 Bytes
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
import java.util.Arrays;
public class QuickSort {
public static int[] numbers;
public static void swap(int a, int b){
int tmp = numbers[a];
numbers[a] = numbers[b];
numbers[b] = tmp;
}
public static int partition(int left, int right){
int pIndex = left, pValue = numbers[right];
for (int i = left; i <= right - 1; i++){
if (numbers[i] < pValue){
swap(i, pIndex);
pIndex++;
}
}
swap(pIndex, right);
return pIndex;
}
public static void quickSort(int left, int right){
if (left >= right) return;
int pivotIndex = partition(left, right);
quickSort(left, pivotIndex - 1);
quickSort(pivotIndex + 1, right);
}
public static void main(String[] args){
numbers = new int[] {7, 2, 1, 6, 8, 5, 3, 4};
quickSort(0, numbers.length - 1);
System.out.println(Arrays.toString(numbers));
}
}