Created
December 13, 2018 12:14
-
-
Save SajidK25/38396ecbc1eea51318c564031ce2daf6 to your computer and use it in GitHub Desktop.
Heap, Build a Max-heap and Convert Binary tree into a Heap using Dart programming Language
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int left(int i) { | |
return 2 * i; | |
} | |
int right(int i) { | |
return 2 * i - 1; | |
} | |
int parant(int i) { | |
return i; | |
} | |
bool isMaxheap(heap) { | |
int n = heap.length - 1; | |
for (int i = n; i > 0; i--) { | |
int p = parant(i); | |
if (heap[p] < heap[i]) { | |
return false; | |
} else | |
true; | |
} | |
} | |
List maxHeapify(List heap, int heap_size, var i) { | |
int l = left(i); | |
int r = right(i); | |
int largest; | |
if (l <= heap_size && heap[l] > heap[i]) { | |
largest = l; | |
} else | |
largest = i; | |
if (r <= heap_size && heap[r] > heap[largest]) { | |
largest = r; | |
} | |
if (largest != i) { | |
// swap(heap[i], heap[largest]); | |
var temp = heap[i]; | |
heap[i] = heap[largest]; | |
heap[largest] = temp; | |
maxHeapify(heap, heap_size, largest); | |
} | |
} | |
List buildMaxHeap(List heap) { | |
int heap_size = heap.length - 1; | |
for (var i = heap_size / ~2; i < 0; i--) { | |
maxHeapify(heap, heap_size, i); | |
} | |
} | |
main(List<String> args) { | |
List H = [null, 19, 7, 12, 3, 5, 17, 10, 1, 2]; | |
print(H); | |
maxHeapify(H, 9, 3); | |
print(H); | |
print("========================================"); | |
List h = [null, 1, 2, 3]; | |
print(h); | |
maxHeapify(h, 3, 1); | |
print(h); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment