-
-
Notifications
You must be signed in to change notification settings - Fork 60
/
Java Sorting Algorithm
83 lines (72 loc) · 1.75 KB
/
Java Sorting Algorithm
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
import java.util.Arrays;
public class PancakeSort
{
int[] heap;
public String toString() {
String info = "";
for (int x: heap)
info += x + " ";
return info;
}
public void flip(int n) {
for (int i = 0; i < (n+1) / 2; ++i) {
int tmp = heap[i];
heap[i] = heap[n-i];
heap[n-i] = tmp;
}
// System.out.println("flip(0.." + n + "): " + toString());
}
public int[] minmax(int n) {
int xm, xM;
xm = xM = heap[0];
int posm = 0, posM = 0;
for (int i = 1; i < n; ++i) {
if (heap[i] < xm) {
xm = heap[i];
posm = i;
}
else if (heap[i] > xM) {
xM = heap[i];
posM = i;
}
}
return new int[] {posm, posM};
}
public void sort(int n, int dir) {
if (n == 0) return;
int[] mM = minmax(n);
int bestXPos = mM[dir];
int altXPos = mM[1-dir];
boolean flipped = false;
if (bestXPos == n-1) {
--n;
}
else if (bestXPos == 0) {
flip(n-1);
--n;
}
else if (altXPos == n-1) {
dir = 1-dir;
--n;
flipped = true;
}
else {
flip(bestXPos); }
sort(n, dir);
if (flipped) {
flip(n);
}
}
PancakeSort(int[] numbers) {
heap = numbers;
sort(numbers.length, 1);
}
public static void main(String[] args) {
int numbers[] = {7, -5, 3, 2, 1, 0, 45};
System.out.println("Original Array:");
System.out.println(Arrays.toString(numbers));
PancakeSort pancakes = new PancakeSort(numbers);
System.out.println("Sorted Array:");
System.out.println(Arrays.toString(numbers));
}
}