为什么这种插入排序不起作用?

时间:2019-02-02 23:57:58

标签: java

我创建了一个定义电影对象的电影类。这是测试该类的客户端类。我创建了一种方法,可以按创建年份对Movie对象数组进行排序。在测试程序时,我发现某些Movie对象将被排序,而某些对象将不会。有人可以帮我为什么这不起作用吗?

public class MovieTesterv2 {
public static void main(String[] args) {
    Movie[] movies = {new Movie("Meet the Robinsons", 2007, "Disney"),
            new Movie("Avengers: Infinity War", 2018, "Pinewood"),
            new Movie("Iron Man", 2008, "Tim Miller"),
            new Movie("Aquaman", 2018, "Hollywood"),
            new Movie("Bumblebee", 2018, "Hollywood"),
            new Movie("Transformers", 2007, "Universal"),
            new Movie("The Lion King", 1994, "Disney"),
            new Movie("Mummy", 1999, "Universal"),
            new Movie("Minions", 2015, "Universal"),
            new Movie("Cinderella", 1950, "Disney")};
    insertionYear(movies);
}

public static void printMovies(Movie[] movies) {
    System.out.println("                 Movie     Year       Studio");
    System.out.println("--------------------------------------------");
    for (Movie movie: movies) {
        if (movie != null) {
            System.out.printf("%22s%9s%13s%n", movie.getTitle(),
                    movie.getYear(), movie.getStudio());
        }
    }
}

public static void insertionYear(Movie[] movies) {
    Movie[] sorted = new Movie[movies.length];

    for (int i = 0; i < movies.length; i++) {
        int k = i;
        while (k > 0) {
            if (movies[i].getYear() <= movies[k - 1].getYear()) {
                sorted[k] = sorted[k - 1];
                k--;
            } else {
                break;
            }
        }
        sorted[k] = movies[i];
        printMovies(sorted);
        System.out.println();
    }

    for (int i = 0; i < movies.length; i++) {
        movies[i] = sorted[i];
    }
}

}

这是电影课。

public class Movie
{
    private int year;
    private String title;
    private String studio;

    public Movie(String title, int year, String studio)
    {
        this.title = title;
        this.year = year;
        this.studio = studio;
    }

public String getTitle()
{
    return title;
}

public void setTitle(String title)
{
    this.title = title;
}

public String getStudio()
{
    return studio;
}

public void setStudio(String studio)
{
    this.studio = studio;
}

public int getYear()
{
    return year;
}

public void setYear(int year)
{
    this.year = year;
}

public String toString()
{
    String str = String.format("%-30s %4d   %-20s", title, year, studio);
    return str;
}

}

2 个答案:

答案 0 :(得分:1)

看这行:

if (movies[i].getYear() <= movies[k - 1].getYear()) {

您想将电影与已排序列表而不是其自己的电影列表进行比较。

答案 1 :(得分:0)

您不会像插入排序那样将每个元素与已排序列表进行比较。在这一行,

if (movies[i].getYear() <= movies[k - 1].getYear())

您将要迭代的当前电影与原始列表中的当前电影进行比较。应将其更改为

if (movies[i].getYear() <= sorted[k - 1].getYear())

原因是,现在您正在将索引i中的当前电影与索引中小于i的电影进行排序。这样,您可以在到目前为止的已排序电影中找到当前电影的正确位置。