Skip to content

Commit b8c9905

Browse files
committed
add pancakesort
1 parent 0826d7a commit b8c9905

2 files changed

Lines changed: 29 additions & 1 deletion

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package app.sort;
2+
3+
import app.core.Ops;
4+
5+
public class PancakeSort extends NamedSort {
6+
public PancakeSort() { super("Pancake Sort"); }
7+
8+
@Override
9+
public void generate(int[] a, Ops ops) {
10+
for (int size = a.length; size > 1; size--) {
11+
int maxIdx = 0;
12+
for (int i = 1; i < size; i++) if (a[i] > a[maxIdx]) maxIdx = i;
13+
if (maxIdx == size - 1) continue;
14+
if (maxIdx > 0) flip(a, ops, maxIdx);
15+
flip(a, ops, size - 1);
16+
}
17+
}
18+
19+
void flip(int[] a, Ops ops, int end) {
20+
int i = 0, j = end;
21+
while (i < j) {
22+
ops.swap(a, i, j);
23+
i++;
24+
j--;
25+
}
26+
}
27+
}

src/main/java/app/sort/Sorts.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ private Sorts() {}
2525
new PigeonholeSort(),
2626
new CycleSort(),
2727
new BitonicSort(),
28-
new ExternalMergeSort()
28+
new ExternalMergeSort(),
29+
new PancakeSort()
2930
);
3031
}

0 commit comments

Comments
 (0)