Presentation is loading. Please wait.

Presentation is loading. Please wait.

Priority Queues Linked-list Insert Æ Æ head head

Similar presentations


Presentation on theme: "Priority Queues Linked-list Insert Æ Æ head head"— Presentation transcript:

1 Priority Queues Linked-list Insert Æ Æ head head 9 2 5 8 10 15 2 5 8

2 Time Complexity Insert: Delete: n deletions and insertions: O(n) O(1)

3 Heap A max (min) heap is a complete binary tree such that the data stored in each node is greater (smaller) than the data stored in its children, if any.

4 20 8 15 4 10 7 2 8 7 6 2

5 Larger than its parent 20 8 15 4 10 7 9 Not a heap

6 Not a complete tree – Not a heap
Missing left child 25 12 10 5 9 7 11 1 6 3 8 Not a complete tree – Not a heap

7 Storing a Complete Binary Tree in an Array
1 3 2 5 4 7 6 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 for any node at index i parent = i/ left child = i * 2 right child = i*2+1

8 Insert into a Heap (top down)
Store the data in a variable, say “t” Determine the next node position Start from the root node and until the insertion position is reached, do Compare the value of “t” with the data in the current node. If it is greater than swap. Insert “t”

9 Insert into a heap (bottom-up)
Store the data in the next available location Compare with parent If parent is smaller then swap with parent Go to step 2 and repeat the process until the current node is at the top or parent is larger.

10 16 22 22 24 3 t 24 t 25 22 20 18 15 7 16 8 9 10 11 12 25 24 25 25 22 25 24 16 7 24 16 22 3 7 Insert 24 – Insert 3 –

11 16 22 22 24 3 t 24 t 25 22 20 18 15 7 16 8 9 10 11 12 25 24 25 25 22 25 24 16 7 24 16 22 3 7 Insert 24 – Insert 3 –

12 25 24 20 18 15 7 16 8 9 10 11 12 22 3 3 24 3 25 22 3 3 16 25 delete Last Node# 14

13 Heap Sort // top down insert
void insertIntoHeap(int a[], int size, int key) { int i, j, k; i = size; a[size] = key; k = i; j = i/2; while (j > 0 && a[j] < a[k]) { swap(a[j], a[k]); k = j; j = j/2; }

14 Heap Sort void putLargestAtTheEndAndReadjustHeap(int a[], int size) {
int i,j, left, right; swap(a[1], a[size]); i = 1; while ((i*2) < size) { left = i*2; right = i*2+1; largest = i; if (left < size && a[left] > a[largest]) largest = left; if (right < size && a[right] > a[largest]) largest = right; if (largest == i) break; else swap(a[i], a[largest]); i = largest; }

15 Heap Sort void heapSort(int a[], int size) { int i;
for(i = 1; i <= size; i++) insertIntoHeap(a, i, a[i]); putLargestAtTheEndAndReadjustHeap(a, size – i + 1); }


Download ppt "Priority Queues Linked-list Insert Æ Æ head head"

Similar presentations


Ads by Google