Skip to content

Commit

Permalink
Add heap sort priority queue example
Browse files Browse the repository at this point in the history
  • Loading branch information
epatrizio committed Jan 25, 2022
1 parent de5af09 commit 6796489
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 3 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ cds
cds_test
intl
!intl/
sort
!sort/
/tests/lib/

# vsc
Expand Down
6 changes: 5 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,8 @@ compile_test:

compile_example_intl:
gcc -g -o intl -Wall -Wextra \
src/vector.c src/hash_utils.c src/hash_map.c examples/intl/intl.c examples/intl/main.c
src/vector.c src/hash_utils.c src/hash_map.c examples/intl/intl.c examples/intl/main.c

compile_example_sort:
gcc -g -o sort -Wall -Wextra \
src/vector.c src/priority_queue.c examples/sort/main.c
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@ Implementations are inspired by this [blog post](https://www.journaldev.com/3523
Execute "make compile_test" and that's all!\
I use the framework [ctestfmk](https://github.com/epatrizio/ctestfmk). Read the documentation for more informations.

## Example
## Examples

In /example directory, you can find a complete application of HashMap data structure:\
* In /examples/intl directory, there is a complete application of HashMap data structure:\
A little internationalization component.

* In /examples/sort directory, there is a classic and easy application of priority queue data structure:\
The array heap sort. For simplicity, only the int type has been processed.
39 changes: 39 additions & 0 deletions examples/sort/main.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "../../src/vector.h"
#include "../../src/priority_queue.h"

/*
This implementation of heapsort is very easy and work well.
But it requires 2 arrays : the initial array to sort and the temp priority queue array.
It's possible to have a more efficient (in memory) implementation with only the initial array :
https://en.wikipedia.org/wiki/Heapsort
*/
void heap_sort(int a[], size_t size)
{
int_priority_queue pq = int_priority_queue_create();

for (unsigned int i = 0 ; i < size ; i++)
int_priority_queue_push(pq, a[i]);

for (unsigned int i = 0 ; i < size ; i++)
a[i] = int_priority_queue_pop(pq);

int_priority_queue_destroy(pq);
}

int main()
{
int a[] = { 0, 25, 32, 10, 1, 50, 20, 100, -1, 27, 28, 10, 3, 99, -10, -1, 110, 55, 75, -2, 0 };
size_t size = sizeof(a) / sizeof(int);

heap_sort(a,size);

for (unsigned int i = 0 ; i < size ; i++)
printf("%i:%i\n", i, a[i]);

return EXIT_SUCCESS;
}

0 comments on commit 6796489

Please sign in to comment.