MCPcopy Index your code
hub / github.com/careercup/ctci / mergesort

Method mergesort

java/Chapter 3/Question3_6/Question.java:9–58  ·  view source on GitHub ↗
(Stack<Integer> inStack)

Source from the content-addressed store, hash-verified

7public class Question {
8 static int c = 0;
9 public static Stack<Integer> mergesort(Stack<Integer> inStack) {
10 if (inStack.size() <= 1) {
11 return inStack;
12 }
13
14 Stack<Integer> left = new Stack<Integer>();
15 Stack<Integer> right = new Stack<Integer>();
16 int count = 0;
17 while (inStack.size() != 0) {
18 count++;
19 c++;
20 if (count % 2 == 0) {
21 left.push(inStack.pop());
22 } else {
23 right.push(inStack.pop());
24 }
25 }
26
27 left = mergesort(left);
28 right = mergesort(right);
29
30 while (left.size() > 0 || right.size() > 0)
31 {
32 if (left.size() == 0)
33 {
34 inStack.push(right.pop());
35 }
36 else if (right.size() == 0)
37 {
38 inStack.push(left.pop());
39 }
40 else if (right.peek().compareTo(left.peek()) <= 0)
41 {
42 inStack.push(left.pop());
43 }
44 else
45 {
46 inStack.push(right.pop());
47 }
48 }
49
50 Stack<Integer> reverseStack = new Stack<Integer>();
51 while (inStack.size() > 0)
52 {
53 c++;
54 reverseStack.push(inStack.pop());
55 }
56
57 return reverseStack;
58 }
59
60 public static Stack<Integer> sort(Stack<Integer> s) {
61 Stack<Integer> r = new Stack<Integer>();

Callers 1

mainMethod · 0.95

Calls 5

pushMethod · 0.95
popMethod · 0.95
peekMethod · 0.95
compareToMethod · 0.80
sizeMethod · 0.45

Tested by

no test coverage detected