forked from careercup/ctci
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuestion.java
More file actions
92 lines (82 loc) · 1.86 KB
/
Question.java
File metadata and controls
92 lines (82 loc) · 1.86 KB
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
package Question3_6;
import java.util.Stack;
import CtCILibrary.AssortedMethods;
public class Question {
static int c = 0;
public static Stack<Integer> mergesort(Stack<Integer> inStack) {
if (inStack.size() <= 1) {
return inStack;
}
Stack<Integer> left = new Stack<Integer>();
Stack<Integer> right = new Stack<Integer>();
int count = 0;
while (inStack.size() != 0) {
count++;
c++;
if (count % 2 == 0) {
left.push(inStack.pop());
} else {
right.push(inStack.pop());
}
}
left = mergesort(left);
right = mergesort(right);
while (left.size() > 0 || right.size() > 0)
{
if (left.size() == 0)
{
inStack.push(right.pop());
}
else if (right.size() == 0)
{
inStack.push(left.pop());
}
else if (right.peek().compareTo(left.peek()) <= 0)
{
inStack.push(left.pop());
}
else
{
inStack.push(right.pop());
}
}
Stack<Integer> reverseStack = new Stack<Integer>();
while (inStack.size() > 0)
{
c++;
reverseStack.push(inStack.pop());
}
return reverseStack;
}
public static Stack<Integer> sort(Stack<Integer> s) {
Stack<Integer> r = new Stack<Integer>();
while(!s.isEmpty()) {
int tmp = s.pop();
while(!r.isEmpty() && r.peek() > tmp) {
s.push(r.pop());
}
r.push(tmp);
}
return r;
}
public static void main(String [] args) {
for (int k = 1; k < 100; k++) {
c = 0;
Stack<Integer> s = new Stack<Integer>();
for (int i = 0; i < 10 * k; i++) {
int r = AssortedMethods.randomIntInRange(0, 1000);
s.push(r);
}
s = mergesort(s);
int last = Integer.MAX_VALUE;
while(!s.isEmpty()) {
int curr = s.pop();
if (curr > last) {
System.out.println("Error: " + last + " " + curr);
}
last = curr;
}
System.out.println(c);
}
}
}