Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>This is heap_sort which uses heapify and max heap concepts. I coded as per the algorithm in "Intro to Algos" book. Have a look. #include "stdafx.h" #define LEFT(i) (2 * (i)) #define RIGHT(i) (((2 * (i)) + 1)) #define PARENT(i) ((i) / 2)) void print_heap(int input[], int n) { int i; printf("Printing heap: \n"); for (i = 0; i &lt; n; i++) printf("%d ", input[i]); printf("\n"); } void swap_nodes(int *a, int *b) { int tmp; tmp = *a; *a = *b; *b = tmp; } void max_heapify(int input[], int i, int n) { int largest; int l = LEFT(i + 1) - 1; // Get 0 based array index int r = RIGHT(i + 1) - 1; // Get 0 based array index if (l &lt; n &amp;&amp; input[l] &gt; input[i]) { largest = l; } else { largest = i; } if (r &lt; n &amp;&amp; input[r] &gt; input[largest]) { largest = r; } if (largest != i) { swap_nodes(&amp;input[i], &amp;input[largest]); max_heapify(input, largest, n); } } void heapify(int input[], int n) { for (int i = n/2; i &gt;= 0; i--) max_heapify(input, i, n); } void heap_sort(int input[], int n) { heapify(input, n); for (int i = n - 1; i &gt;= 1; i--) { swap_nodes(&amp;input[0], &amp;input[i]); n = n - 1; max_heapify(input, 0, n); } } int _tmain(int argc, _TCHAR* argv[]) { //int input[] = {6, 5, 3, 1, 8, 7, 4, 2}; //int input[] = {4, 1, 3, 2, 16, 9, 10, 14, 8, 7}; int input[] = {5, 3, 17, 10, 84, 19, 6, 22, 9, 1}; //int input[] = {16, 14, 10, 8, 7, 9, 3, 2, 4, 1}; int n = sizeof(input) / sizeof(input[0]); print_heap(input, n); heap_sort(input, n); print_heap(input, n); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload