Skip to content

Commit dde3106

Browse files
committed
Add Quick Sort in Java
1 parent 42cda25 commit dde3106

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

QuickSort/Java/QuickSort.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.dev.namhoai.sort;
2+
3+
public class QuickSort {
4+
public static void sort(int[] a) {
5+
sort(a, 0, a.length - 1);
6+
}
7+
8+
public static void sort(int[] a, int low, int high) {
9+
if (low >= high) return;
10+
11+
int middle = partition(a, low, high);
12+
sort(a, low, middle - 1);
13+
sort(a, middle + 1, high);
14+
}
15+
16+
private static int partition(int[] a, int low, int high) {
17+
int middle = low + (high - low) / 2;
18+
swap(a, middle, high);
19+
int storeIndex = low;
20+
for (int i = low; i < high; i++) {
21+
if (a[i] < a[high]) {
22+
swap(a, storeIndex, i);
23+
storeIndex++;
24+
}
25+
}
26+
swap(a, high, storeIndex);
27+
return storeIndex;
28+
}
29+
30+
private static void swap(int[] a, int i, int j) {
31+
int temp = a[i];
32+
a[i] = a[j];
33+
a[j] = temp;
34+
}
35+
}

0 commit comments

Comments
 (0)