-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathStackSort.java
118 lines (95 loc) · 2.15 KB
/
StackSort.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*
Sort Stack: Write a program to sort a stack such that the smallest items are on the top. You can use
an additional temporary stack, but you may not copy the elements into any other data structure
(such as an array). The stack supports the following operations: push, pop, peek, and is Empty.
*/
import java.util.*;
public class DoNotCommit {
public static void main(String args[]) {
Stack s = new Stack(5);
s.push(48);
s.push(36);
s.push(1);
s.push(-1);
s.push(0);
while (!s.isEmpty()) {
System.out.println(s.pop());
}
}
public static int[] sort(Stack s) {
int length = s.length();
divideArray(s.getArr(), 0, length - 1);
return s.getArr();
}
public static int[] divideArray(int[] arr, int lIndex, int hIndex) {
if (lIndex < hIndex) {
int middle = lIndex + (hIndex - lIndex) / 2;
divideArray(arr, lIndex, middle);
divideArray(arr, middle + 1, hIndex);
mergeArray(arr, lIndex, middle, hIndex);
}
return arr;
}
public static int[] mergeArray(int[] arr, int lIndex, int middle, int hIndex) {
int[] tempArr = new int[arr.length];
System.arraycopy(arr, 0, tempArr, 0, arr.length);
int start = lIndex;
int end = middle + 1;
int i = lIndex;
;
while (start <= middle && end <= hIndex) {
if (tempArr[start] <= tempArr[end]) {
arr[i] = tempArr[start];
start++;
} else {
arr[i] = tempArr[end];
end++;
}
i++;
}
while (start <= middle) {
arr[i] = tempArr[start];
i++;
start++;
}
return arr;
}
}
class Stack {
private int[] arr;
private int top;
int length() {
return top + 1;
}
Stack(int n) {
this.arr = new int[n];
this.top = -1;
}
boolean isEmpty() {
return top == -1 ? true : false;
}
void push(int x) {
arr[++top] = x;
}
int pop() {
if (top == -1) {
throw new EmptyStackException();
}
return arr[top--];
}
int peek() {
return arr[top];
}
public int[] getArr() {
return arr;
}
public void setArr(int[] arr) {
this.arr = arr;
}
public int getTop() {
return top;
}
public void setTop(int top) {
this.top = top;
}
}