| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| Original | -99 | 13 | 21 | 16 | 24 | 31 | 19 | 68 | 65 | 26 | 32 | |
| After i=11 | -99 | 13 | 21 | 16 | 24 | 19 | 68 | 65 | 26 | 32 | 31 | |
| After i=5 | -99 | 13 | 16 | 24 | 21 | 19 | 68 | 65 | 26 | 32 | 31 | |
| After i=2 | -99 | 13 | 14 | 16 | 24 | 21 | 19 | 68 | 65 | 26 | 32 | 31 |
For new value 14: i=++size
Child i has parent at i/2
Parent j has children possibly at 2j and 2j+1.
Compare and swap
Sentinel is smallest possible value
Is the data sorted?
Priority queue: operating systems, simulation
Array Heaps: minheap [119]
void insert(element_type x, PRIORITY_QUEUE H); element_type delete_min(PRIORITY_QUEUE H); % gcc -o minheap minheap.c -lm > tcc minheap.c % minheap > h h(elp; q(uit; i(nsert x; D(elete_min; d(isplay_tree; s(how_array
Data File with Test Cases: minheap.dat
i 21 s i 13 s i 19 s i 65 s i 32 s i 16 s i 68 s i 24 s i 26 s i 31 s d i 14 s d D s d
Array Heaps: minheap.dat [120]
[ 21 ]
[ 13 21 ]
[ 13 21 19 ]
[ 13 21 19 65 ]
[ 13 21 19 65 32 ]
[ 13 21 16 65 32 19 ]
[ 13 21 16 65 32 19 68 ]
[ 13 21 16 24 32 19 68 65 ]
[ 13 21 16 24 32 19 68 65 26 ]
[ 13 21 16 24 31 19 68 65 26 32 ]
Priority queue or (min)Heap as Binary Tree:
13
21 16
24 31 19 68
65 26 32
Insert 14:
[ 13 14 16 24 21 19 68 65 26 32 31 ]
Priority queue or (min)Heap as Binary Tree:
13
14 16
24 21 19 68
65 26 32 31
Array Heaps: minheap.dat [121]
Min: 13
[ 14 21 16 24 31 19 68 65 26 32 ]
Priority queue or (min)Heap as Binary Tree:
14
21 16
24 31 19 68
65 26 32
ANALYSIS:
How deep is the binary tree: O( )
To insert new element at bottom, and percolate up: O( )
To delete top element, and iteratively replace with smaller children: O( )
Array Heaps: minheap.c [122]
#define MAX_ELEMENTS 100
typedef int element_type;
struct heap_struct {
unsigned int max_heap_size;
unsigned int size;
element_type elements[MAX_ELEMENTS];
};
typedef struct heap_struct *PRIORITY_QUEUE;
void insert(element_type x, PRIORITY_QUEUE H) {
int i;
if (H->size == H->max_heap_size)
printf("Priority queue is full\n");
else {
i = ++H->size;
while (H->elements[i/2] > x) { /* while parent greater than child */
H->elements[i] = H-> elements[i/2]; /* half of a swap */
i /= 2;
}
H->elements[i] = x;
}
}
element_type delete_min(PRIORITY_QUEUE H) {
unsigned int i, child;
element_type min_element, last_element;
if (H->size == 0)
printf("Priority queue is empty\n");
else {
min_element = H->elements[1];
last_element = H->elements[H->size--]; /* let "heavy" perc down */
for (i=1; 2*i <= H->size; i=child) {
child = 2*i;
/* find smaller child */
if ((child != H->size) && (H->elements[child+1] < H->elements[child]))
child++;
/* percolate one level */
if (last_element > H->elements[child])
H->elements[i] = H->elements[child]; /* half of a swap */
else
break;
}
H->elements[i] = last_element;
return(min_element);
}
}