text: The following Java class HeapSorter encapsulates the functions downheap, buildheap and heapsort. In order to sort an array b, Heapsort is called with the statement HeapSorter.sort(b). \n\npublic class HeapSorter \n{\n    private static int[] a;\n    private static int n;\n\n    public static void sort(int[] a0)\n    {\n        a=a0;\n        n=a.length;\n        heapsort();\n    }\n\n\n    private static void heapsort()\n    {\n        buildheap();\n        while (n>1)\n        {\n            n--;\n            exchange (0, n);\n            downheap (0);\n        } \n    }\n\n\n    private static void buildheap()\n    {\n        for (int v=n/2-1; v>=0; v--)\n            downheap (v);\n    }\n\n\n    private static void downheap(int v)\n    {\n        int w=2*v+1;    // first descendant of v\n        while (w<n)\n        {\n            if (w+1<n)    // is there a second descendant?\n                if (a[w+1]>a[w]) w++;\n            // w is the descendant of v with maximum label\n\n            if (a[v]>=a[w]) return;  // v has heap property\n            // otherwise\n            exchange(v, w);  // exchange labels of v and w\n            v=w;        // continue\n            w=2*v+1;\n        }\n    }\n\n\n    private static void exchange(int i, int j)\n    {\n        int t=a[i];\n        a[i]=a[j];\n        a[j]=t;\n    }\n\n}    // end class HeapSorter