#include <iostream>
#define parent(i)  i/2
#define left(i)  2*i
#define right(i)  2*i+1

using namespace std;

/*
  function:  heapsort.
*/

void swap(int *a, int *b)
{
  int tmp;
  tmp = *a;
  *a = *b;
  *b = tmp;
}

void max_heapify(int *a, int i,int N) //保持堆的性质(递归版)
{ 
  int l ;
  int r;
  int largest = -1;
  l = left(i);
  r = right(i);

  if(l <= N && a[l] > a[i])
	  largest = l;
  else
	  largest = i;
  if(r <= N && a[r] > a[largest])
	  largest = r;
  if(largest != i)
  {
    swap(&a[i],&a[largest]);
	max_heapify(a,largest,N);
  }
 
}

void max_heapify2(int *a, int i, int N) //保持堆的性质(迭代版)
{
  int j;
  while(2*i <= N)
  {
    j = 2*i;
	if(j <= N &&a[j] < a[j+1])
		j++;
	if(!(a[i] < a[j]))
		break;
	swap(&a[i],&a[j]);
	i = j;


  }
}

void build_max_heap(int *a, int l, int r)  // 建堆
{
  int i;
  for(i = r/2; i >= 1  ; i--)
	  max_heapify2(a,i,r);
}

void heap_sort(int *a,int l, int r) //堆排
{ 
  int i;
  int len = r - l ;
  build_max_heap(a,l,r);
  
  for(i = len; i >= 2; i--)
  {
	  swap(&a[1],&a[i]);
	  printf("maxi is %d and is %d\n",a[i],i);
	  len--;
	  max_heapify(a,l,len);
  }
  
}


int main()
{ 
  int i;
  int a[11] = {0,4,1,3,2,16,9,10,14,8,7};
  
  heap_sort(a,1,11);

  printf("after sort:\n");
  for(i = 1; i < 11; i++)
  {
    printf("%d\n",a[i]);
  }
  
  return 0;
}