/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.broad.igv.util;

import java.util.Comparator;

public class ArrayHeapSorter {

    private int[] a;
    private int n;
    Comparator<Integer> c;

    public void sort(int[] a0) {
        a = a0;
        n = a.length;
        this.c =  null;
        heapsort();
    }

    public void sort(int[] a0, Comparator<Integer> c) {
        a = a0;
        n = a.length;
        this.c = c;
        heapsort();
    }

    private void heapsort() {
        buildheap();
        while (n > 1) {
            n--;
            exchange(0, n);
            downheap(0);
        }
    }

    private void buildheap() {
        for (int v = n / 2 - 1; v >= 0; v--) {
            downheap(v);
        }
    }

    private void downheap(int v) {
        int w = 2 * v + 1;    // first descendant of v
        while (w < n) {
            if (w + 1 < n) // is there a second descendant?
            {
                if (c == null) {
                    if (a[w + 1] > a[w]) {
                        w++;
                    }
                } else {
                    if (c.compare(a[w + 1], a[w]) > 0) {
                        w++;
                    }
                }
            }
            // w is the descendant of v with maximum label

            if (c == null) {
                if(a[v] >= a[w]) {
                    return;
                }
            } else {
                if (c.compare(a[v], a[w]) >= 0) {
                    return;  // v has heap property
                }            // otherwise
            }
            exchange(v, w);  // exchange labels of v and w
            v = w;        // continue
            w = 2 * v + 1;
        }
    }

    private void exchange(int i, int j) {
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
} 