-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSortIterative.java
More file actions
45 lines (40 loc) · 909 Bytes
/
QuickSortIterative.java
File metadata and controls
45 lines (40 loc) · 909 Bytes
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
import java.util.Arrays;
import java.util.Stack;
public class Solution{
public static void main(String args[]){
int[] arr = {1,2,1,1,1};
QuickSort(arr,0,arr.length-1);
System.out.println(Arrays.toString(arr));
}
public static void QuickSort(int[] arr, int low, int high){
Stack<Integer> st = new Stack<Integer>();
st.push(low);
st.push(high);
int l,h;
while(!st.isEmpty()){
h = st.pop();
l = st.pop();
if(l < h){
int p = partition(arr,l,h);
st.push(l); st.push(p-1);
st.push(p+1); st.push(h);
}
}
}
public static int partition(int[] arr, int low, int pivot){
int i = low-1;
for(int j = low; j < pivot; j++){
if(arr[j] < arr[pivot]){
i++;
swap(arr,i,j);
}
}
swap(arr,++i,pivot);
return i;
}
public static void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}