-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathQuickSort.java
More file actions
52 lines (41 loc) · 1.26 KB
/
QuickSort.java
File metadata and controls
52 lines (41 loc) · 1.26 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
public class QuickSort {
public static void main(String[] args) {
int[] array = {9, 7, 5, 11, 12, 2, 14, 3, 10, 6};
int n = array.length;
System.out.println("Original array:");
printArray(array);
quickSort(array, 0, n - 1);
System.out.println("Sorted array:");
printArray(array);
}
public static void quickSort(int[] array, int low, int high) {
if (low < high) {
int pivotIndex = partition(array, low, high);
quickSort(array, low, pivotIndex - 1);
quickSort(array, pivotIndex + 1, high);
}
}
public static int partition(int[] array, int low, int high) {
int pivot = array[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (array[j] < pivot) {
i++;
swap(array, i, j);
}
}
swap(array, i + 1, high);
return i + 1;
}
public static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void printArray(int[] array) {
for (int num : array) {
System.out.print(num + " ");
}
System.out.println();
}
}