-
Notifications
You must be signed in to change notification settings - Fork 688
/
QuickSort.java
63 lines (51 loc) · 1.79 KB
/
QuickSort.java
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
60
61
62
63
package sort;
import java.util.Arrays;
public class QuickSort {
/*
* Given an integer array, sort it in ascending order using quicksort.
*
* Runtime Complexity - Linearithmic, O(nlogn).
* Memory Complexity - Logarithmic, O(logn).
* Note: Recursive solution has O(logn) memory complexity as it will consume memory on the stack.
*
*
* Step 1: Select a pivot element from the array, usually the first element
* Step 2: Compare the pivot element with the current element. If the current element is less than the pivot,
* shift the current element to the left side and if it is greater than the pivot, shift it to the right
* side of the pivot.
* Step 3: Recursively sort the sublists on the right and left sides of the pivot
* */
public static int[] quickSort(int[] arr, int low, int high) {
if(high > low) {
int partitionIndex = partition(arr, low, high);
quickSort(arr, low, partitionIndex-1);
quickSort(arr, partitionIndex+1, high);
}
return arr;
}
private static int partition(int[]arr, int low, int high) {
int pivot = arr[low];
int i=low;
int j = high;
while (i < j) {
while (i<= high && arr[i] <= pivot) {
i++;
}
while (arr[j] > pivot) {
j--;
}
if(i < j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
} else break;
}
arr[low] = arr[j];
arr[j] = pivot;
return j;
}
public static void main(String[] args) {
int[] arr = {55, 23, 26, 2, 25};
System.out.print(Arrays.toString(quickSort(arr, 0, arr.length-1)));
}
}