Skip to content

Commit 041ca29

Browse files
author
Thodoras
committed
.
1 parent eeab793 commit 041ca29

File tree

1 file changed

+113
-0
lines changed

1 file changed

+113
-0
lines changed

Diff for: Sorting/Heap.java

+113
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
public class Heap<Key extends Comparable<Key>> {
2+
// Heap data structure that supports insertion (O(logN)), deletion of minimum (O(logN)),
3+
// and heapsort (O(NlogN), deterministic, stable).
4+
5+
private int size;
6+
private Key[] array;
7+
8+
public Heap() {
9+
size = 0;
10+
array = (Key[]) new Comparable[1];
11+
}
12+
13+
public Heap(Key[] keys) {
14+
size = keys.length;
15+
int length = convSize(size);
16+
array = (Key[]) new Comparable[length];
17+
for (int i = 0; i < size; i++) {
18+
array[i] = keys[i];
19+
}
20+
heapsort();
21+
}
22+
23+
public void heapsort() {
24+
int temp = size / 2 - 1;
25+
for (int i = temp; i >= 0; i--) {
26+
sink(i);
27+
}
28+
}
29+
30+
public boolean isEmpty() {
31+
return size == 0;
32+
}
33+
34+
public void insert(Key key) {
35+
array[size++] = key;
36+
if (size == array.length)
37+
resize(2*array.length);
38+
swim();
39+
}
40+
41+
public Key removeMin() {
42+
Key value = array[0];
43+
exch(0, size - 1);
44+
array[--size] = null;
45+
if (size <= array.length/4) {
46+
resize(array.length/4);
47+
}
48+
sink(0);
49+
return value;
50+
}
51+
52+
public void print() {
53+
for (int i = 0; i < size; i++)
54+
System.out.println(array[i]);
55+
}
56+
57+
private void swim() {
58+
int temp = size;
59+
while (temp > 1) {
60+
if (less(array[temp-1], array[temp/2 - 1])) {
61+
exch(temp-1, temp/2 - 1);
62+
temp /= 2;
63+
}
64+
else {
65+
break;
66+
}
67+
}
68+
}
69+
70+
private void sink(int pos) {
71+
pos += 1;
72+
while (2 * pos <= size) {
73+
int min = minIndex(2*pos -1, 2*pos);
74+
if (less(array[min], array[pos - 1])) {
75+
exch(min, pos - 1);
76+
pos *= min + 1;
77+
}
78+
else {
79+
break;
80+
}
81+
}
82+
}
83+
84+
private void exch(int i, int j) {
85+
Key swap = array[i];
86+
array[i] = array[j];
87+
array[j] = swap;
88+
}
89+
90+
private boolean less(Key x, Key y) {
91+
return x.compareTo(y) < 0;
92+
}
93+
94+
private int convSize(int n) {
95+
return (int) Math.pow(2, Math.ceil(Math.log(n) / Math.log(2)));
96+
}
97+
98+
private int minIndex(int i, int j) {
99+
if (i == size) {return j;}
100+
if (j == size) {return i;}
101+
if (less(array[j], array[i]))
102+
return j;
103+
else
104+
return i;
105+
}
106+
107+
private void resize(int tolength) {
108+
Key[] temp = (Key[]) new Comparable[tolength];
109+
for (int i = 0; i < size; i++)
110+
temp[i] = array[i];
111+
array = temp;
112+
}
113+
}

0 commit comments

Comments
 (0)