forked from sarthakd999/Hacktoberfest2021-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
IterativeQSort.java
68 lines (55 loc) · 1.65 KB
/
IterativeQSort.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
64
65
66
67
68
import java.util.Arrays;
import java.util.Scanner;
import java.util.Stack;
public class Sorting {
public static void main(String args[]) {
int[] unsorted = { 34, 32, 43, 12, 11, 32, 22, 21, 32 };
System.out.println("Unsorted array : " + Arrays.toString(unsorted));
iterativeQsort(unsorted);
System.out.println("Sorted array : " + Arrays.toString(unsorted));
}
public static void iterativeQsort(int[] numbers) {
Stack stack = new Stack();
stack.push(0);
stack.push(numbers.length);
while (!stack.isEmpty()) {
int end = stack.pop();
int start = stack.pop();
if (end - start < 2) {
continue;
}
int p = start + ((end - start) / 2);
p = partition(numbers, p, start, end);
stack.push(p + 1);
stack.push(end);
stack.push(start);
stack.push(p);
}
}
private static int partition(int[] input, int position, int start, int end) {
int l = start;
int h = end - 2;
int piv = input[position];
swap(input, position, end - 1);
while (l < h) {
if (input[l] < piv) {
l++;
} else if (input[h] >= piv) {
h--;
} else {
swap(input, l, h);
}
}
int idx = h;
if (input[h] < piv) {
idx++;
}
swap(input, end - 1, idx);
return idx;
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}