Heapsort

Hi, I'm trying to implement the Heapsort algorithm, but it is not sorting properly, can anyone please review.
I'm sorting an array from 1 to n
public class HeapSort {
     //Sorts an array of data of the specified type, using the heap sort algorithm,
     //and returns the number of comparisons made.
     public void heapSort(java.lang.Comparable[] data){
          int n=data.length-1;
          buildMaxHeap(data);
          for(int i=n;i>=2;i--){
               Comparable temp=data[1];
               data[1]=data;
               data[i]=temp;
               --n;
               maxHeapify(data,1,n);
     //Sorts the first heapSize elements of array A, using heap sort.
     //Assumes heapSize is less than or equal to A.length.
     public void heapSort(java.lang.Comparable[] A, int heapSize) {
          for(int i=A.length-1;i>1;i--) {
               Comparable temp=A[1];
               A[1]= A[i];
               A[i]=temp;
               --heapSize;
               maxHeapify(A,1,heapSize);
     public void buildMaxHeap(java.lang.Comparable[] A){
          int hs=A.length-1;
          for(int i=hs/2;i>1;i--){
               maxHeapify(A,i,hs);
     public void maxHeapify(java.lang.Comparable[] A, int badIndex, int heapSize){
          int left=2*badIndex;
          int right=2*badIndex+1;
          int largest;
          if(left<=heapSize && A[left].compareTo(A[badIndex]) > 0) {
               largest=left;
          else {
               largest=badIndex;
          if(right <=heapSize && A[right].compareTo(A[largest])>0) {
               largest=right;
          if(largest!=badIndex){
               Comparable temp=A[badIndex];
               A[badIndex]=A[largest];
               A[largest]=temp;
               maxHeapify (A,largest,badIndex);

This is my code:
public class HeapSort {
     //Sorts an array of data of the specified type, using the heap sort algorithm,
     //and returns the number of comparisons made.
     public void heapSort(java.lang.Comparable[] data){
          int n=data.length-1;
          buildMaxHeap(data);
          for(int i=n;i>=2;i--){
               Comparable temp=data[1];
               data[1]=data;
               data[i]=temp;
               --n;
               maxHeapify(data,1,n);
     //Sorts the first heapSize elements of array A, using heap sort.
     //Assumes heapSize is less than or equal to A.length.
     public void heapSort(java.lang.Comparable[] A, int heapSize) {
          for(int i=A.length-1;i>1;i--) {
               Comparable temp=A[1];
               A[1]= A[i];
               A[i]=temp;
               --heapSize;
               maxHeapify(A,1,heapSize);
     public void buildMaxHeap(java.lang.Comparable[] A){
          int hs=A.length-1;
          for(int i=hs/2;i>1;i--){
               maxHeapify(A,i,hs);
     public void maxHeapify(java.lang.Comparable[] A, int badIndex, int heapSize){
          int left=2*badIndex;
          int right=2*badIndex+1;
          int largest;
          if(left<=heapSize && A[left].compareTo(A[badIndex]) > 0) {
               largest=left;
          else {
               largest=badIndex;
          if(right <=heapSize && A[right].compareTo(A[largest])>0) {
               largest=right;
          if(largest!=badIndex){
               Comparable temp=A[badIndex];
               A[badIndex]=A[largest];
               A[largest]=temp;
               maxHeapify (A,largest,badIndex);

Similar Messages

  • Help with heapsort.  Pretty new to java

    Hello,
    I am following a tutorial on heapsort for my java class. I implemented it but the problem is this. The first element in the array i pass in is never changed. Here is the code. What am i doing wrong from this tutorial. What should i do?
    public static <T extends Comparable<T>> void heapSort(T[] array)
            heapit(array.length - 1,array);
      public static<T extends Comparable<T>>void swap(int i, int j,T[] array)
          T temp = array[j];
           array[j] = array;
    array[i] = temp;
    public static <T extends Comparable<T>>void heapit( int end,T[] array )
    for ( int i = end / 2; i >= 1; i-- )
    fixheap( i, end, array[i],array );
    for ( int i = end; i > 1; i-- )
    swap( 1, i,array );
    fixheap( 1,i - 1 , array[1],array );
    public static <T extends Comparable<T>>void fixheap( int root, int end,
    T key,T[] array )
    int child = 2 * root;
    if ( child < end && array[child].compareTo(array[child + 1]) < 0 )
    child++;
    if ( child <= end && key.compareTo(array[child])< 0 )
    array[root] = array[child];
    fixheap( child, end, key,array );
    else
    array[root] = key;

    ejp wrote:
    It's usual to use 1-based indexing in heapsort algorithms.
    So maybe the problem is that you are expecting element[0] to be sorted and it isn't? which it won't be, because of the 1-basing.{noformat}
    There's nothing a little math can't cure: for a 1 based algorithm a node at position i has its children at position 2*i and 2*i+1 so for a 0 based indexin scheme the node is at position j+1 and its children are at position 2*(j+1) and 2*(j+1)+1. Because the nodes are stored one position to the left the children of node j are 2*(j+1)-1 and 2*(j+1)+1-1.{noformat}
    kind regards,
    Jos

  • Heap Sort

    Hi, I'm writing a code for Heap Sort, to sort an array of Comparables from 1 to n
    But it is not working, can some one please look at my code and tell me where I'm wrong, Please.........
    public class HeapSort {
         //Sorts an array of data of the specified type, using the heap sort algorithm,
         //and returns the number of comparisons made.
         public void heapSort(java.lang.Comparable[] data){
              int n=data.length-1;
              buildMaxHeap(data);
              for(int i=n;i>=2;i--){
                   Comparable temp=data[1];
                   data[1]=data;
                   data[i]=temp;
                   --n;
                   maxHeapify(data,1,n);
         //Sorts the first heapSize elements of array A, using heap sort.
         //Assumes heapSize is less than or equal to A.length.
         public void heapSort(java.lang.Comparable[] A, int heapSize) {
              for(int i=A.length-1;i>1;i--) {
                   Comparable temp=A[1];
                   A[1]= A[i];
                   A[i]=temp;
                   --heapSize;
                   maxHeapify(A,1,heapSize);
         public void buildMaxHeap(java.lang.Comparable[] A){
              int hs=A.length-1;
              for(int i=hs/2;i>1;i--){
                   maxHeapify(A,i,hs);
         public void maxHeapify(java.lang.Comparable[] A, int badIndex, int heapSize){
              int left=2*badIndex;
              int right=2*badIndex+1;
              int largest;
              if(left<=heapSize && A[left].compareTo(A[badIndex]) > 0) {
                   largest=left;
              else {
                   largest=badIndex;
              if(right <=heapSize && A[right].compareTo(A[largest])>0) {
                   largest=right;
              if(largest!=badIndex){
                   Comparable temp=A[badIndex];
                   A[badIndex]=A[largest];
                   A[largest]=temp;
                   maxHeapify (A,largest,badIndex);

    public class HeapSort {
         //Sorts an array of data of the specified type, using the heap sort algorithm,
         //and returns the number of comparisons made.
         public void heapSort(java.lang.Comparable[] data){
              int n=data.length-1;
              buildMaxHeap(data);
              for(int i=n;i>=2;i--){
                   Comparable temp=data[1];
                   data[1]=data;
                   data[i]=temp;
                   --n;
                   maxHeapify(data,1,n);
         //Sorts the first heapSize elements of array A, using heap sort.
         //Assumes heapSize is less than or equal to A.length.
         public void heapSort(java.lang.Comparable[] A, int heapSize) {
              for(int i=A.length-1;i>1;i--) {
                   Comparable temp=A[1];
                   A[1]= A[i];
                   A[i]=temp;
                   --heapSize;
                   maxHeapify(A,1,heapSize);
         public void buildMaxHeap(java.lang.Comparable[] A){
              int hs=A.length-1;
              for(int i=hs/2;i>1;i--){
                   maxHeapify(A,i,hs);
         public void maxHeapify(java.lang.Comparable[] A, int badIndex, int heapSize){
              int left=2*badIndex;
              int right=2*badIndex+1;
              int largest;
              if(left<=heapSize && A[left].compareTo(A[badIndex]) > 0) {
                   largest=left;
              else {
                   largest=badIndex;
              if(right <=heapSize && A[right].compareTo(A[largest])>0) {
                   largest=right;
              if(largest!=badIndex){
                   Comparable temp=A[badIndex];
                   A[badIndex]=A[largest];
                   A[largest]=temp;
                   maxHeapify (A,largest,badIndex);

  • Sorting by timestamp?

    I have a program on "Priority Queues" in which basically, using an array, I hafta have a list of people stored based on their priority. Thats not the problem. The problem occurs when two people have the same priority. To solve this we're supposed to use Timestamps which I have. Every Patient has a timestamp but I'm not sure how to incorporate them into the program to determine how to sort them. If that doesn't make sense, here's some code.....
    public void add(Object obj)
         if (maxIndex+1<capacity) // maxIndex is # Patients in array pq , capacity is pq.length
                   pq[maxIndex+1]=(Patient)obj;
              else
                   resize(); //changes capacity
                   pq[maxIndex+1]=(Patient)obj;
              maxIndex++;
              int[] temp1=new int[maxIndex+1];           
              for (int i=1;i<temp1.length; i++)// makes a list of the priorities of each patient
                   temp1=pq[i].getP();
              HeapSort.Sort (temp1); //this code works, it sorts by order of priority
              toPatients(pq,temp1);     matches up a patient with its priority                         
    public void toPatients(Patient[] patients, int[] priorities)//swaps things around in pq to make patients inorder by priotiy
              for (int j=1; j<priorities.length; j++)
                   for (int i=1; i<priorities.length; i++)
                        if(priorities[j]==patients[i].getP())
                             Patient hold=patients[j];
                             patients[j]=patients[i];
                             patients[i]=hold;
                             break;
    all patients have a timestamp so if i were to say patients[i].time() I would get the nanoseconds that they've been on the list but I'm not sure where to put that in this code so that they will be sorted by time if they have the same priority

    I have a program on "Priority QueuesSo is your assignment on using "Priority Queues" (note the plural form of queues) or on how to write your own Sort routine????
    As I suggested in your other post create a separate queue for each priority, then is no need to do a sort.
    If you are going to ask a homework assignment question, then the least you can do is specify the correct requirements so we don't waste our time providing solutions you can't use. (ie. you already rejected the solution to use Collections.sort() in your other thread).

  • Sorting an array of numbers with loops

    Hi, i'm looking for a way to sort an array or numbers with loops.
    my array looks like this. int[] numbers = {5,2,7,9,1}
    i know how to use the "sort" method and i want to do it without the sort method, but i am not very clear on the logic behind it.
    by the end it should look like this, {1,2,5,7,9}
    i know 2 loops are used, can you please give me a logic to work with.
    i have started the loops but what to do inside???
    int temp;
    for (int i=0; i<numbers.length; i++){
    for (int j=1; j<numbers; j++){
    if (numbers<numbers[j])
    temp = numbers[i];
    Any suggestions i will be thankful for.
    thank you.

    fly wrote:
    no not really a homework question.. i want to improve my logic because it is very poor at the moment.. but i'm sure someone knows how to sort an array with loops only.Yes, we do know how to do it, I once wrote a heapsort in assembly code, as a real work project. But you rarely get a project like that the good ones were all done years ago.
    All the algorithms I suggested you look at use loops. the simplest and slowest is the bubble sort. This one runs by comparing values and swapping their locations, the wikipedia article http://en.wikipedia.org/wiki/Bubble_sort has the algorithm.

  • Adding to a Linked Complete Binary Tree

    Hi all,
    I am having major trouble trying to grasp the concept behind adding to a Complete Binary Tree (linked structure). It is part of a much larger assignment that uses a Heap Priority Queue and I am genuinely stuck. I have noticed that there seems to be some sort of strike going on so I wont expect a reply to this.
    I understand that Binary Tree's are useful because of their recursive nature, does the process of adding use recursion also. My mind is a mess at the moment so forgive the rambling. My problem exists when I go to add after a right child on a lower level(anything below level 3). I have come to the conclusion that I it is impossible to continue with my adding method and that I should scrap it. Can anyone point anything relevant out to me? I'd appreciate it, thank you.
    public class LinkedBT implements CompleteBT
         private BTNode root;          //a reference to the root node
         private BTNode current;          //a reference to the last inserted node
         private BTNode firstNodeInLevel; //a reference to the first node in the level
         private int size;               //keeps track of the size of the BT
         private int currentLevel;
         private int leafCount;
         public LinkedBT()
              root = null;     //instantiate instance variables
              current = null;
              size = 0;
              currentLevel = 0;     //indicates that there are no nodes
              leafCount = 0;
              firstNodeInLevel = null;
         public boolean isEmpty()     
              return (root==null);
         public int size()
              return size;
         public void add(Object obj, int priority)
              BTNode tempNode = new BTNode(obj, priority);
              tempNode.parent = current;                                   //set the parent of the node to current
              if(isEmpty())                                             //if the tree is empty then make a new BTNode and give it the root reference
                   root = tempNode;     
                   current = root;                                        //make current reference to the root node
                   size++;
                   currentLevel++;                //increments currentLevel
                   return;                          //return control to calling method
              if(current.childrenFull!=true)          //if the current node has available children positions then check left and right and add BTNode appropriately
                   if(current.leftChild==null)
                        if(leafCount==0)     //if this is the first node to be added on any given level then.....
                             firstNodeInLevel = tempNode;     //.....store a reference to it for future adding purposes
                        current.leftChild = tempNode;     //adds BTNode to left child
                        leafCount++;
                   else
                        current.rightChild = tempNode;          //add BTNode to right child
                        leafCount++;
                        current.childrenFull = true;          //after adding the right child set the childrenFull property true NECESSARY?????
                        if(Math.pow(2, currentLevel)==leafCount)     //IF THIS EVALS TO TRUE THEN THE MAX NUMBER OF LEAVES FOR THAT LEVEL IS REACHED
                             currentLevel++;     //increment the level
                             leafCount = 0;     //reset the leaf count
                             current = firstNodeInLevel;          //change current to the furthest leaf on the left
                        else     //ELSE NEED TO GO BACK UP AND FIND NEXT FEASIBLE POSITION
                             //while(current.parent.rightChild.leftChild.)----------------THIS DOESNT WORK WHEN THE TREE GETS BIGGER
                                  //current = current.parent; //set current to next feasible position
              size++;
         public Object getRoot()
              return root;
         public void heapSort()
         private class BTNode
              private Object value;
              private int key;
              private BTNode parent;
              private BTNode leftChild;
              private BTNode rightChild;
              private boolean childrenFull;      //initially false, when both children are occupied then change to true
              private BTNode(Object obj, int priority)     //constructor accepts the value and the priority key
                   value = obj;          
                   key = priority;
                   parent = null;
                   leftChild = null;
                   rightChild = null;
                   childrenFull = false;
              public boolean hasNoChildren()
                   return(leftChild==null && rightChild==null);     //returns true if the node has no children
    }

    Currently working on setting the Linked Servers Security properties. Added the SQLAgent in the" Local server login to remote server login mappings:". The SQLAgent is the only entry in the grid. The SQLAgent has the Remote User and Remote Password
    of the AS400. Then below have "Not be made" for "For a login not defined in the lst above, connections will:".
    So provided that the SQL Admin only gives SQL Job create, Job Alter and Alter Linked Server to user/groups that he wants to use the linked server the Admin can control access to the linked server.
    Any thoughts?

  • Sorting & Pagination

    Hi All,
    all query services should support Pagination and Sorting. Pl ensure respective implementations covers below fields as support:
    -     pageNumber and pageSize should be received in request
    -     total record count along with pagenumber and pagesize should be part of response.
    Please let me know , How i will acheive this in AIA.
    Regards,
    rupesh

    @jagabandhu: I've looked at the code and I like the idea of putting another TableModel layer in between the data and the table. But I'm not too happy about implementing everything myself. If I can get a library of some kind to do the work I would prefer that. Also, Bubble sort? really? I would have gone with a mergesort or a heapsort for the initial data and an insertion sort after that.
    @StanislavL: that code looks great and I'm going to try to use it, it may be a little to heavy for my needs but I'm sure I can modify it. One point though; the website doesn't say anything about the license this code is released under. I'm ok with LGPL or anything freer like MIT, BSD, Apache, etc. The GPL isn't acceptable.
    I also noticed the XML viewer component you have on the website, I would like to use that one too, so again what license is that code released under?

  • Shortest Path Algorithm:

    Hi,
    I have about 20,000 (double) points and trying to find a shortest path between any two. I know that the best algorithm for doing that is Dijkstra's one. What is the best data structure for this? I read that usually heaps but the time it needs to sort the list is too long, maybe some one knows a better way? Maybe there is another algorithm that solves this problem? Please give me any suggestion about anything that I said above.
    Thank you in advance.

    I don't know no Dijkstra's algorithm for this problem. The only algorithm of Dijkstra for something like that that I know is to find the shortest path between two nodes in a weight network.
    I think that the lower bound for what you are trying to do is the same lower bound for sorting the points, so I think that the best you can do is to apply a good sorting algorithm (like quicksort, mergesort, heapsort or shellsort).
    The best data structure depends about how much info do you have previously about the number of points and memory that you have available. If you know that the max number of points that you'll work can be fit in the available memory, then the best data holder to use is an array (it's aways the fastest). If you'll see it as an array or as stack (for example) depends on the algorithm that you'll choose to sort the points.
    One last tip: if you choose using a List, prefer the ArrayList over LinkedList. LinkedList is slower than ArrayList for almost all kind of operations. If you'll work with a lot of elemts, do some testing before pick one of the two.
    Hope it helps,
    RGB

  • Better way to sort multi dim int array

    I'm tracking key value pairs of ints. I know that the keys will not repeat. I've decided to do this in an int[][] array
    int[][] data = new int[2][many millions]This app crunches a lot of data so I'm shooting for the best memory handling. I push a bunch of key - value pairs into the array. I will likely populate many if not all data and not have to search until I'm done populating so I'm not sorting as I go.
    I know that I can sort the single dim array data[0] but how can I keep the values array data[1] synchronized? I've tried a few things, all have been successful but I'm wondering if there's a better method. Currently I create copy arrays for the keys and values, sort the original keys, and loop through the copy keys. For each copy key I binary search the sorted keys and drop the value in the correct spot. I don't like having to allocate 2X the amount of memory for the swap arrays. Any thoughts?
    Thanks
    ST

    Jos, thanks for the reply. I tried this method but I don't get as much
    storage since each internal array counts as an object.Yes I know; maybe I've got something for you, waidaminnit <dig-dig/>
    <shuffle-shuffle/> Ah, got it. Suppose you wrap your two dim array in
    a simple class that implements this interface:public interface Sortable {
         public int length();
         public int compare(int i, int j);
         public void swap(int i, int j);
    }I think the semantics of the methods are obvious. Given this interface
    you can sort anything you like using this thingy:public class HeapSort {
         private Sortable s;
         private void heapify(int i, int n) {
              for (int r, l= (i<<1)+1; l < n; i= l, l= (i<<1)+1) {
                   if ((r= l+1) < n && s.compare(l, r) < 0) l= r;
                   if (s.compare(i, l) < 0) s.swap(i, l);
         private void phase1() {
              for (int n= s.length(), i= n/2; i >= 0; i--)
                   heapify(i, n);
         private void phase2() {
              for (int n= s.length(); --n > 0; ) {
                   s.swap(0, n);
                   heapify(0, n);
         public HeapSort(Sortable s) { this.s= s; }
         public Sortable sort() {
              phase1();
              phase2();
              return s;
    }kind regards,
    Jos

  • Help in understanding some code

    I am new to java and need some help in understanding what the setHeapWithSize method does listed below. Thanks
    public class HeapSort {
    public void heapsort(int[] a){
              int [] A = setHeapWithSize(a, a.length);
              buildHeap(A);
              for (int i = a.length; i>1; i--){
                   a[i-1] = A[0];
                   A[0] = a[i-1];
                   A=setHeapWithSize (A, A.length-1);
                   heapify(a, 1);
                   a[0] = A[0];
         public void buildHeap (int[] a) {
              for (int i = a.length/2; i>0; i--){
              heapify(a, i);
         public void heapify (int[] a, int i){
              int l = left(i);
              int r = right(i);
              int largest;
              if (l<= heapSize(a) && a[i-1]>a[i-1]){
              largest = l;
              else{
              largest=i;
              if (r<=heapSize(a) && a[r-1]> a[largest-1]){
              largest = r;
              if (largest != i){
              int tmp = a[i-1];
              a[i-1] = a[largest-1];
              a[largest-1] = tmp;
              heapify(a, largest);
         public int heapSize (int [] a){
         return a.length;
         public int parent (int i){
         return(i/2);
         public int left (int i){
         return (2*i);
         public int right (int i){
         return (2*i +1);
         }>

    I am new to java and need some help in understanding
    what the setHeapWithSize method does listed below.Don't you think it would be a smart move to show us the code for setHeapWithSize? Or do you want us to make a wild guess at what it does based on its name?

Maybe you are looking for

  • IPod Shuffle not recognized by computer

    iTunes keeps telling me that my shuffle is not fomatted properly and I have to restore. But even after restoring, I still keep getting the same error message. What can I do?

  • Can I set up an account in the US store and the Australia store?

    My iStore app seams to have switched from the US store to the Australia store.  How do I get back to the US store or set up an account in the Australia store?

  • How can I do calculation positioning in crosstab?

    I have a calculation that should be displayed in only one column, at the right of a crosstab. Discoverer insists to copy my calculation under all columns, repeating the same result under each. Is their a way to fix it at one place?

  • I cannot auto capitalise when i compose email in apple mail

    Dear All,     i am using IMac Pc running snow leopard 10.6.7 , when i composing by apple mail first letter always is coming small letter, auto capitalisation is not working.. Kindly i requesting you if this feature not availiable in mac at all ..plea

  • Dump occured in standard program SAPMV45A (order creation)

    hi, In order creation, a dump is occured in standard program SAPMV45A. Because of in FM "Pricing_Dialog_Tabstrips" is incorrect and TAXI_TABSTRIP_C and TAXI_TABSTRIP_ITEM" specified here is a different field type.This is standard program we can not c