Skip to content

Commit ab49890

Browse files
committed
Created Java Quick Sort Implementation
1 parent 1ebf8b7 commit ab49890

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Sorting/QuickSort.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
public class QuickSort {
2+
3+
public static void quickSort(int[] arr) {
4+
quickSort(arr, 0, arr.length-1);
5+
}
6+
7+
public static void quickSort(int[] arr, int leftIndex, int rightIndex) {
8+
int arrLength = rightIndex + 1 - leftIndex;
9+
10+
if (arrLength > 1) {
11+
int partitionIndex = partition(arr, leftIndex, rightIndex);
12+
13+
quickSort(arr, leftIndex, partitionIndex-1);
14+
quickSort(arr, partitionIndex+1, rightIndex);
15+
}
16+
}
17+
18+
public static int partition(int[] arr, int leftIndex, int rightIndex) {
19+
int pivot = arr[rightIndex];
20+
int partitionIndex = leftIndex;
21+
22+
for (int i = leftIndex; i < rightIndex; i++) {
23+
if (arr[i] < pivot) {
24+
swap(arr, i, partitionIndex);
25+
partitionIndex++;
26+
}
27+
}
28+
swap(arr, partitionIndex, rightIndex);
29+
30+
return partitionIndex;
31+
}
32+
33+
public static void swap(int[] arr, int i, int j) {
34+
int temp = arr[i];
35+
arr[i] = arr[j];
36+
arr[j] = temp;
37+
}
38+
}

0 commit comments

Comments
 (0)