В этом году я пытаюсь работать впереди в своем классе алгоритмов: D, и я делаю работу в классе (поэтому она не помечена или не оценена как таковая, но только для практики, я полагаю, приведу к части курсовой работы)
В любом случае - нам дали список имен в виде текстового файла, который принимает следующий формат
"surname, first name"
и каждому предмету присваивается номер записи (который на данный момент не актуален)
мы должны переписать метод поиска, используя пример полу псевдокода, который он дал нам, где я застреваю. (первоначально метод поиска массива был следующим)
/**
* Look a name and return the number or null if there is no match
*/
public String search(String name)
{
for (int i = 0; i < length; i++) {
if (name.equals(list[i].getName())) {
return list[i].getNumber();
}
}
return null;
}
Текстовое описание из слайдов лекции говорит о том, что мы можем сделать реализацию следующим образом;
1) Use variables to store the start-index and length of the sequence of array elements that must contain this entry if there is one.
2) Set start-index to 0 and length to the array length.
3) while length is greater than 1
a) Compare Mike with the name in the middle element (at start_index + length/2)
b) If it is earlier then set length to length/2 and leave start-index as it is.
c) If it is later or equal then add length/2 to start-index and subtract length/2 from length
4) length is now 1 so it must be Mike's entry if he has one
Здесь моя реализация, но я получаю исключение нулевого указателя на
java.lang.NullPointerException
at PhoneBook.search(PhoneBook.java:73) (if(name.comeToIgnoreCase... )
at PhoneBook.testSearch(PhoneBook.java:57)
public String search (String name)
{
int startIndex = 0;
int length = list.length;
while(length > 1){
if(name.compareToIgnoreCase(list[startIndex + (length / 2)].getName()) > 0) {
length = length / 2;
}
else {
startIndex = startIndex + (length / 2);
length = length - (length / 2);
}
if (length == 1){
return list[length].getName();
}
}
return null;
}