我需要有一个按字母顺序排序的学生数据库,所以我决定通过正确插入来保持学生的排序。所以我决定使用insert方法实现二进制搜索,以便在插入时对其进行排序。
但是,由于某种原因,它插入不正确,并且数据库不再排序。我知道它与我的逻辑与.compareToIgnoreCase()方法有关。这是我的代码:
private Student[] binaryInsert(Student student, int min, int max) {
int mid = (min + max) / 2;
if (min > max) {
return insert(studentDatabase, student, -1);
}
if (min == max) {
if (studentDatabase[mid].compareToIgnoreCase(student)) < 0) {
return insert(studentDatabase, student, mid + 1);
} else {
return insert(studentDatabase, student, mid - 1);
}
} else if (studentDatabase[mid].compareToIgnoreCase(student)) < 0) {
return binaryInsert(student, mid + 1, max);
} else {// last possibility: a[mid] > x
return binaryInsert(student, min, mid - 1);
}
}
public Student[] insert(Student[] database, Student object, int i) {
Student[] newDatabase = new Student[database.length + 1];
if (i == -1) {
for (int j = 1; j < newDatabase.length; j++) {
newDatabase[j] = database[j - 1];
}
newDatabase[0] = object;
} else {
for (int x = 0; x < i; x++) {
newDatabase[x] = database[x];
}
newDatabase[i] = object;
for (int x = i + 1; x < newDatabase.length; x++) {
newDatabase[x] = database[x - 1];
}
}
return newDatabase;
}
我的意见:
STUDENT/NAD86/RAFAEL/NADAL/1986/SPAIN
STUDENT/DJO87/NOVAK/DJOKOVIC/1987/SERBIA
STUDENT/FED81/ROGER/FEDERER/1981/SWITZERLAND
STUDENT/STA86/ALEX/STAIRS/1998/AMERICA
我的输出
FED81: ROGER FEDERER, 1981, SWITZERLAND, 0.0
DJO87: NOVAK DJOKOVIC, 1987, SERBIA, 0.0
NAD86: RAFAEL NADAL, 1986, SPAIN, 0.0
STA86: ALEX STAIRS, 1998, AMERICA, 0.0
FED81是问题孩子。如果我重新安排输入,它确实有用,但我无法做到。
提前感谢您的帮助!
编辑:应该注意的是,我尝试了相同的过程,但使用了整数,并且它在我的所有测试中都有效。
答案 0 :(得分:0)
感谢Joop Eggen,我能够让它运转起来。解决方案是取出&#34; - 1&#34;来自insert(studentDatabase, student, mid - 1)
方法调用。
修复是因为[i]之前的插入点是i,而不是i - 1.
归功于Joop Eggen!