Skip to content

Commit 946fad6

Browse files
committed
sorting: HeapSort
1 parent 1987276 commit 946fad6

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
* sorts a sequence of strings from standard input using heapsort.
3+
* The `HeapSort` class provides a static methods for heapsorting an array.
4+
*
5+
*/
6+
public class HeapSort{
7+
private HeapSort() {}
8+
9+
// rearranges the array in ascending order, using the natural order.
10+
public static void sort(Comparable[] pq) {
11+
int n = pq.length;
12+
for(int k = n / 2; k >= 1; k--) {
13+
sink(pq, k, n);
14+
}
15+
16+
while(n > 1){
17+
exchange(pa, 1, n--);
18+
sink(pq, 1, n);
19+
}
20+
}
21+
22+
// Helper functions
23+
private static void sink(Comparable[] pq, int k, int n) {
24+
while(2 * k <= n) {
25+
int j = 2 * k;
26+
if(j < n && less(pq, j, j + 1))
27+
j++;
28+
if(!less(pq, k, j))
29+
break;
30+
exchange(pq, k, j);
31+
k = j;
32+
}
33+
}
34+
35+
// helper functions for comparisons and swaps
36+
// indices are "off-by-one" to support 1-based indexing.
37+
private static boolean less(Comparable[] pq, int i, int j) {
38+
return pq[i - 1].compareTo(pq[j - 1]) < 0;
39+
}
40+
41+
private static void exchange(Object[] pq, int i, int j) {
42+
Object swap = pq[i - 1];
43+
pq[i - 1] = pq[j - 1];
44+
pq[j - 1] = swap;
45+
}
46+
47+
// print
48+
private static void show(Comparable[] a) {
49+
for(int i = 0; i < a.length; i++) {
50+
StdOut.println(a[i]);
51+
}
52+
}
53+
54+
// test
55+
public static void main(String[] args) {
56+
String[] a = StdIn.readAllStrings();
57+
Heap.sort(a);
58+
show(a);
59+
}
60+
}

0 commit comments

Comments
 (0)