Implements a Heapsort - Java Data Structure

Java examples for Data Structure:Sort

Description

Implements a Heapsort

Demo Code

import static java.lang.System.out;


public class Heap {

    private static void sink (Comparable[] pq, int k, int N) {
      while (2 * k <= N) {
          int j = 2 * k;
          if (j < N && less(pq, j, j+1))
              j++;//from  ww w . j  a v  a2  s  .  c o  m
        
          if (!less(pq, k, j))
              break;
        
          exch(pq, k, j);
          k = j;
      }
    }
    
    private static void exch(Object[] pq, int i, int j) {
        Object swap = pq[i-1];
        pq[i-1] = pq[j-1];
        pq[j-1] = swap;
    }

    private static boolean less(Comparable[] pq, int i, int j) {
        return pq[i-1].compareTo(pq[j-1]) < 0;
    }
    
    public static void sort(Comparable[] pq) {
      int N = pq.length;
      
      for (int k = N/2; k >= 1; k--) 
          sink(pq, k, N);
      
      while (N > 1) {
          exch(pq, 1, N--);
          sink(pq, 1, N);
      }
    }
    
    public static void main(String[] args) {
      Integer[] data = new Integer[] {5, 1, 3, 7, 4, 8, 1, 38, 10, 9, 8, 44};
        sort(data);
        
        out.print("Array sorted by Heapsort: ");
        for (Integer x: data) {
            out.printf("%s ",x);
        }
    }
}

Related Tutorials