简体   繁体   中英

Bubble sorting an object array in Java

how do I sort an array of objects? this is my code for sorting the array, I receive a "not a statement" error for: Movie temp = movies[b]; what do i declare the temp variable as if it is to hold the exact value/reference of movies[b]; which could be any of three different object types which are in the same array? I am new to programming so I apologize if i seem to be ignorant; please feel free to correct me or ask questions if I phrased the questions incorrectly.

public static String bubbleSort(Movie[] movies) {
    for (int a=1; a<movies.length; a++) {
        for(int b=0; b<movies.length - a; b++) {
            if (((movies[b].getTitle()).compareTo((movies[b+1].getTitle()))) > 0)
                //swap movies[b] with movies[b+1]
                Movie temp = movies[b];
            movies[b] = movies[b+1];
            movies[b+1] = temp;
        }
    }
}

When an array is defined as Movie[] it can only contains objects of type Movie . So you can only have Movie s in there. However, to make this general, you should define the type as Object and the array as Object[] .

However, in your code, you are assuming that you really do have Movie objects because you're using Movie.getTitle() . You will not be able to access that from references of Object . I would recommend having your objects implement Comparable and using the type Comparable as the type of the array and your temporary variable.

The Movie temp = movies[b]; is a declaration, not a statement. You want this:

        if (((movies[b].getTitle()).compareTo((movies[b+1].getTitle()))) > 0)
        {
            //swap movies[b] with movies[b+1]
            Movie temp = movies[b];
            movies[b] = movies[b+1];
            movies[b+1] = temp;
        }

Note all I did was add braces around all the swap code, making it into a block which can contain a declaration. I think this is what you intended, but just omitted the braces.

使用Collections API,不要重新发明轮子进行自己的排序实现。

You were missing a { after the test, and incorrectly promising to return a String. Try this,

public static void bubbleSort(Movie[] movies) {
    for (int a = 1; a < movies.length; a++) {
        for (int b = 0; b < movies.length - a; b++) {
            if (((movies[b].getTitle())
                    .compareTo((movies[b + 1].getTitle()))) > 0) {
                // swap movies[b] with movies[b+1]
                Movie temp = movies[b];
                movies[b] = movies[b + 1];
                movies[b + 1] = temp;
            }
        }
    }
}

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