Skip to content

Commit 079ad97

Browse files
committed
Add PrintWorstCase.java
1 parent 2a24a98 commit 079ad97

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

PrintWorstCase.java

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import java.util.Set;
2+
import java.util.HashSet;
3+
4+
public class PrintWorstCase {
5+
private static final int MIN_MERGE = 32;
6+
private static final Set<Integer> WORST_CASE = new HashSet<Integer>();
7+
8+
private static int minRun;
9+
10+
public static void main(String[] args) {
11+
System.out.println(" Array size Stack Size");
12+
for(int len=MIN_MERGE; len>0; len++) {
13+
int size = Math.max(JDKWorstCase(len), correctWorstCase(len));
14+
if(!WORST_CASE.contains(size)) {
15+
WORST_CASE.add(size);
16+
System.out.printf("%11d %9d\n", len, size);
17+
}
18+
}
19+
}
20+
21+
private static void setBound(long len) {
22+
minRun = minRunLength(len);
23+
}
24+
25+
private static int minRunLength(long n) {
26+
assert n >= 0;
27+
int r = 0; // Becomes 1 if any 1 bits are shifted off
28+
while (n >= MIN_MERGE) {
29+
r |= (n & 1);
30+
n >>= 1;
31+
}
32+
return (int)n + r;
33+
}
34+
35+
private static long first(long total) {
36+
if( (8*minRun+9 <= total)
37+
|| (5*minRun+5 <= total && total <= 8*minRun+1)
38+
|| (3*minRun+3 <= total && total <= 4*minRun+1)) {
39+
return minRun+1;
40+
}
41+
while(total >= 2*minRun+1)
42+
total=total/2+1;
43+
return total;
44+
}
45+
46+
public static int JDKWorstCase(long length) {
47+
setBound(length);
48+
int stackSize=0;
49+
long runningTotal=0, curr=minRun+4, prev=minRun;
50+
51+
while(runningTotal+curr+prev <= length) {
52+
runningTotal += prev + curr;
53+
stackSize +=2;
54+
long diff = first(prev);
55+
prev = curr + diff + 1;
56+
curr += prev + 1;
57+
}
58+
59+
if(runningTotal + prev <= length) {
60+
runningTotal += prev;
61+
stackSize++;
62+
}
63+
64+
if(runningTotal < length)
65+
stackSize++;
66+
return stackSize;
67+
}
68+
69+
public static int correctWorstCase(int length) {
70+
setBound(length);
71+
int stackSize=1;
72+
long curr = minRun, prev=0;
73+
long runningTotal = length<minRun ? length : minRun;
74+
75+
while(runningTotal+prev+curr+1 <= length) {
76+
curr += prev+1;
77+
prev=curr-prev-1;
78+
runningTotal += curr;
79+
stackSize++;
80+
}
81+
82+
if(runningTotal < length)
83+
stackSize++;
84+
return stackSize;
85+
}
86+
}

0 commit comments

Comments
 (0)