Heap Sort

void swap(int *a, int *b)
{
    *a = *a + *b;
    *b = *a - *b;
    *a = *a - *b;
}
      
void minHeapify(int a[], int size, int i)
{
    int l = 2*i + 1; //using zero based arrays
    int r = 2*i + 2;
    int smallest = i;
    if(l<size && a[l]<a[smallest])
       smallest = l;
     if(r<size && a[r]<a[smallest])
       smallest = r;
     if(smallest!=i)
     {
         swap(&a[i],&a[smallest]);
         minHeapify(a,size,smallest);
     }        
 }
        
  void buildMinHeap(int a[], int size) {
        for(int i=size/2;i>=0;i--)
            minHeapify(a,size,i);           
}
   
  void heapsort (int a[], int size)
  {      
      buildMinHeap(a,size);     
      while (size > 1)
      {
          swap(&a[0], &ma[size - 1]);
          -- size;  
          minHeapify(a,size,0);
       }      
   }

void removeMin(int a[], int size) 
{ 
    if (isEmpty()) 
         throw new HeapException("Heap is empty"); 
    else { 
         a[0] = a[size - 1]; 
         size--; 
         if (heapSize > 0) 
             minHeapify(a,size,0);
         } 
  }

Leave a comment