Last active
December 11, 2023 03:56
-
-
Save begeekmyfriend/9609ce47145b41d235557df7bad63538 to your computer and use it in GitHub Desktop.
Priority queue
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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
static inline void swap(int *a, int *b) | |
{ | |
int tmp = *a; | |
*a = *b; | |
*b = tmp; | |
} | |
static void show(int *nums, int size) | |
{ | |
int i; | |
for (i = 0; i < size; i++) { | |
printf("%d ", nums[i]); | |
} | |
printf("\n"); | |
} | |
static void min_heapify(int *nums, int size, int parent) | |
{ | |
int i = parent; /* parent is the root */ | |
int l = parent * 2 + 1; | |
int r = parent * 2 + 2; | |
if (l < size && nums[l] < nums[i]) { | |
i = l; | |
} | |
if (r < size && nums[r] < nums[i]) { | |
i = r; | |
} | |
/* percolate up */ | |
if (i != parent) { | |
swap(&nums[i], &nums[parent]); | |
min_heapify(nums, size, i); | |
} | |
} | |
static void build_min_heap(int *nums, int size) | |
{ | |
int i; | |
for (i = size / 2; i >= 0; i--) { | |
min_heapify(nums, size, i); | |
} | |
} | |
int main(void) | |
{ | |
int i, nums[] = { 6, 5, 3, 1, 8, 7, 2, 4 }; | |
int size = sizeof(nums)/sizeof(*nums); | |
build_min_heap(nums, size); | |
show(nums, size); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment