## Labels

algorithms (22) Design Patterns (20) java (19) linux (14) Snippet (13) service mix (6) soa (4)

## Cloudizza ### Heap Sort

`Heap Sort in C++#include < iostream.h >#include < conio.h >int heapSize = 10;void print(int a[]) {  for (int i = 0; i <= 9; i++) {    cout << a[i] << "-";  }  cout << endl;}int parent(int i) {if(i==1)return 0;if(i%2==0)    return ( (i / 2)-1);else    return ( (i / 2));}int left(int i) {  return (2 * i) + 1;}int right(int i) {  return (2 * i) + 2;}void heapify(int a[], int i) {  int l = left(i), great;  int r = right(i);  if ( (a[l] > a[i]) && (l < heapSize)) {    great = l;  }  else {    great = i;  }  if ( (a[r] > a[great]) && (r < heapSize)) {    great = r;  }  if (great != i) {    int temp = a[i];    a[i] = a[great];    a[great] = temp;    heapify(a, great);  }}void BuildMaxHeap(int a[]) {  for (int i = (heapSize - 1) / 2; i >= 0; i--) {    heapify(a, i);    print(a);  }}void HeapSort(int a[]) {  BuildMaxHeap(a);  for (int i = heapSize; i > 0; i--) {    int temp = a;    a = a[heapSize - 1];    a[heapSize - 1] = temp;    heapSize = heapSize - 1;    heapify(a, 0);  }}void main() {  int arr[] = {      2, 9, 3, 6, 1, 4, 5, 7, 0, 8};  HeapSort(arr);  print(arr);}`

1. This comment has been removed by the author.

2. The function heapify() is recursive, which is bad.

You should make this heapsort non-recursive, or it will run out of memory for large arrays.

3. what is da use of parent () function??

4. it gives a better and easier understanding

5. THANK U VERY MUCH. A FABULOUS CODE ,IT HELPED ME IN PROJECT !! :-)

6. should this code work as it is written?

7. how u learn to code like that . I mean its really impressive how u divide big code into small function's . how can i learn to do that ?? any good advice plzzzzzzz. i am in data structure now . and i really wann to make a habit of coding like that . your advice will really gona mean alot !!

8. i do not understand the significance of "heapify(a, great);"..why does this have to be done?