Search code examples
javaheapheapsort

I am trying to sort an array via heapSort and its not working


For some reason, my sortByDuration method will not let me call my remove method to print out the items in my heap as they are being deleted. The purpose of this is just to sort the heap; it really doesn't matter that I am deleting it.

public static Song[] sortByDuration(Song[] songs)//sorts the heap
{
    for(int i=size;i>0;i--)
        System.out.print(songs.remove()+" ");
    return songs;
}

and this is my remove method

public Song remove()//removes
{
    Song retVal = peek();

    heap[0] = heap[size-1];
    heap[size-1] = null;
    size--;

    bubbleDown();

    return retVal;
}

the error is in the print statement of my remove method Thanks guys


Solution

  • You are trying to call the method remove() on an array of objects. Arrays in Java do not have such a method.

    For your code to work properly, you will need to change the way you remove the objects from your songs array. Maybe you want to take a look at "Removing an element from an Array (Java)" question here in SO.

    You may also have missed to index your elements (to access only the i-th element instead of the entire array), and the statement you wanted to write was

            System.out.print(songs[i].remove()+" ");