-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinaryHeap.java
More file actions
70 lines (65 loc) · 1.65 KB
/
BinaryHeap.java
File metadata and controls
70 lines (65 loc) · 1.65 KB
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
import java.util.Arrays;
import java.util.Random;
public class BinaryHeap {
static int a[];
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hi");
CreateArray(10);
int aa[] = a.clone();
long nano = System.nanoTime();
for(int i: a){
System.out.print(i+" ");
}
for(int i=(a.length/2); i>=0; i--){
addRoot(i,a.length);
}
System.out.println((System.nanoTime() - nano));
nano = System.nanoTime();
// insertionSort(aa);
System.out.println((System.nanoTime() - nano));
for(int i: a){
System.out.print(i+" ");
}
}
public static void insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
}
}
public static void addRoot(int index, int length){
int leftChild = index*2;
int swapIndex = leftChild;
if(leftChild < length){
int rightChild = leftChild+1;
if(leftChild+1 < length && a[leftChild] < a[rightChild]){
swapIndex = rightChild;
}
if(a[index] < a[swapIndex]){
int t = a[index];
a[index] = a[swapIndex];
a[swapIndex] = t;
addRoot(swapIndex,length);
}
}
}
public static void CreateArray(int len){
Random r = new Random();
int[] array = new int[len];
for (int a = 0; a < array.length; a++) {
if ((a + 1) % 10 != 0) {
array[a] = (a + 1) * 10;
} else {
array[a] = r.nextInt(1000);
}
}
a = array;
}
}