-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQSort.txt
executable file
·78 lines (66 loc) · 2.72 KB
/
QSort.txt
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.Arrays;
/**
* Java program to Sort integer array using QuickSort algorithm using recursion.
* Recursive QuickSort algorithm, partitioned list into two parts by a pivot,
* and then recursively sorts each list.
* @author Javin Paul
*/
public class QuickSort{
public static void main(String args[]) {
int[] input = { 23, 31, 1, 21, 36, 72};
System.out.println("Before sorting : " + Arrays.toString(input));
quickSort(input); // sort the integer array using quick sort algorithm
System.out.println("After sorting : " + Arrays.toString(input));
// input with duplicates
int[] withDuplicates = { 11, 14, 16, 12, 11, 15};
System.out.println("Before sorting : " + Arrays.toString(withDuplicates));
quickSort(withDuplicates); // sort the integer array using quick sort algorithm
System.out.println("After sorting : " + Arrays.toString(withDuplicates));
}
public static void quickSort(int[] array) {
recursiveQuickSort(array, 0, array.length - 1);
}
public static void recursiveQuickSort(int[] array, int startIdx, int endIdx) {
int idx = partition(array, startIdx, endIdx);
// Recursively call quicksort with left part of the partitioned array
if (startIdx < idx - 1) {
recursiveQuickSort(array, startIdx, idx - 1);
}
// Recursively call quick sort with right part of the partitioned array
if (endIdx > idx) {
recursiveQuickSort(array, idx, endIdx);
}
}
/**
* Divides array from pivot, left side contains elements less than
* Pivot while right side contains elements greater than pivot.
*
* @param array array to partitioned
* @param left lower bound of the array
* @param right upper bound of the array
* @return the partition index
*/
public static int partition(int[] array, int left, int right) {
int pivot = array[left]; // taking first element as pivot
while (left <= right) {
//searching number which is greater than pivot, bottom up
while (array[left] < pivot) {
left++;
}
//searching number which is less than pivot, top down
while (array[right] > pivot) {
right--;
}
// swap the values
if (left <= right) {
int tmp = array[left];
array[left] = array[right];
array[right] = tmp;
//increment left index and decrement right index
left++;
right--;
}
}
return left;
}
}