简体   繁体   中英

Bubble sort java not working

public void sortTracksList()
{
    for(int j=0; j<tracksArray.length; j++)
    {
        for(int k =0; k<(tracksArray.length-1); k++)
        {

            if(tracksArray[k] > tracksArray[k+1])
            {
                int tempTracksArray = tracksArray[k];
                tracksArray[k] = tracksArray[k+1];
                tracksArray[k+1] = tempTracksArray;

            }
        }
    }

    for (int l = 0; l < tracksArray.length; l++)
    {
        System.out.println(tracksArray[l].toString());
    }
}

That's my code and it has 3 errors:

 //if(tracksArray[k] > tracksArray[k+1]) - bad operand types for binary operator
    //int tempTracksArray = tracksArray[k]; - Tracks cannot be converted to int
    //tracksArray[k+1] = tempTracksArray; - int cannot be converted to Tracks

Tracks class:

public class Tracks
{   
    int trackID;
    String trackTitle;
    String trackArtist;
    double trackLength;
    boolean trackOffline;


    public String toString()
    {

        String trackData = trackID + "," +trackTitle + "," + trackArtist + 
        "," + trackLength + "," + trackOffline;
        return trackData;
    }
}

Needs to be sorted by ID

Your code has two issues.

  1. int tempTracksArray = tracksArray[k]; is incorrect. The tracksArray definition is Tracks[] tracksArray ; the array holds objects of type Tracks . Therefore the correct temporary assignment is Tracks tempTracksArray = tracksArray[k];
  2. The > operator is not allowed on objects. Two approaches are shown below to solve this.

Option 1: Compare the integers

for(int j=0; j<tracksArray.length; j++)
{
    for(int k =0; k<(tracksArray.length-1); k++)
    {
        if(tracksArray[k].trackID > tracksArray[k+1].trackID)
        {
            Tracks tempTracksArray = tracksArray[k];
            tracksArray[k] = tracksArray[k+1];
            tracksArray[k+1] = tempTracksArray;

        }
    }
}

Option 2: Use the Comparable interface

for(int j=0; j<tracksArray.length; j++)
{
    for(int k =0; k<(tracksArray.length-1); k++)
    {
        if(tracksArray[k].compareTo(tracksArray[k+1]) > 0)
        {
            Tracks tempTracksArray = tracksArray[k];
            tracksArray[k] = tracksArray[k+1];
            tracksArray[k+1] = tempTracksArray;

        }
    }
}

In which case your Tracks class must implement Comparable:

class Tracks implements Comparable<Tracks> {
    int trackID;
    ......
    @Override
    public int compareTo(Tracks o) {
        return Integer.compare(this.trackID, o.trackID);
    }
}

The second option is preferred. Your Tracks class now has a natural method to describe how it should be sorted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM