我有两个班加主要班。
电影包含info()方法,该方法在main中打印出“插入”。
无论如何,运行代码时,我插入的第三个元素输出两次,覆盖另一个选项。
输出:https://gyazo.com/7374a4546b3f8980f148c995e7ffa833
电影课
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package movieap;
/**
*
* @author T
*/
public class Movie {
String Movie;
int rating;
Movie(String m, int r){
this.Movie = m;
this.rating = r;
}
public void info(){
System.out.println("The movie: " + this.Movie + ", is rated a: " + this.rating);
}
}
MovieArray
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package movieap;
/**
*
* @author T
*/
public class MovieArray {
public Movie[] arrMovie;
public int nElems = 0;
MovieArray(int size) {
arrMovie = new Movie[size];
nElems = 0;
}
public void insert(String m, int rating) {
arrMovie[nElems] = new Movie(m, rating);
nElems++;
}
public void insertSort() {
int in, out;
for (out = 1; out < nElems; out++) {
Movie temp = arrMovie[out];
in = out;
int j = in - 1;
while (in > 1 && arrMovie[j].Movie.compareToIgnoreCase(temp.Movie) >= 0) {
arrMovie[in] = arrMovie[j];
--in;
}
arrMovie[in] = temp;
}
}
public void display() {
for (int i = 0; i < nElems; i++) {
System.out.println(i + 1 + " - ");
arrMovie[i].info();
}
}
}
MovieApp(主要)
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package movieap;
/**
*
* @author T
*/
public class MovieAp {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
MovieArray arrMovie;
arrMovie = new MovieArray(5);
arrMovie.insert("Avengers", 3);
arrMovie.insert("eello", 3);
arrMovie.insert("zes", 6);
arrMovie.insert("co", 4);
System.out.println("The following movies are rated alphabetically");
arrMovie.insertSort();
arrMovie.display();
}
}
输出应按字母顺序对四个选项进行排序,但确实如此,但它的第四个元素会覆盖第三个元素...
您的排序仍然不正确。要查看此内容,请以其他顺序添加电影。根据本文Insertion Sort],这是一种可能的算法
public void insertSort() { int in, out; for (out = 1; out < nElems; out++) { in = out; while (in > 0 && arrMovie[in - 1].Movie.compareToIgnoreCase( arrMovie[in].Movie) >= 0) { Movie temp = arrMovie[in]; arrMovie[in] = arrMovie[in - 1]; arrMovie[in - 1] = temp; --in; } } }
您将在本文中看到,其他算法也提供了一些性能改进。
解决方案>>
因此,在执行此操作后,似乎问题已解决: