📄 chapter9n4.java
字号:
/** * * searching a sorted array * * Written by: Roger Garside * * First Written: 11/Oct/96 * Last Rewritten: 13/Oct/96 * */import java.lancs.* ;public class Chapter9n4 { /** * * main * */ public static void main(String[] args) throws Exception { BasicIo.prompt("type file name: ") ; String fileName = BasicIo.readString() ; // read the data in Person[] personGroup = new Person[100] ; BasicFileIo file = new BasicFileIo(BasicFileIo.INPUT, fileName) ; int noOfPersons = 0 ; while (true) { String fore = file.readString() ; if (fore == null) break ; String sur = file.readString() ; int age = file.readInteger() ; String x = file.readString() ; int gender ; if (x.equalsIgnoreCase("MALE")) gender = Person.MALE ; else if (x.equalsIgnoreCase("FEMALE")) gender = Person.FEMALE ; else gender = Person.UNKNOWN ; personGroup[noOfPersons] = new Person(fore, sur, age, gender) ; noOfPersons++ ; } file.closeFile() ; // display the (unsorted) data for (int i = 0 ; i < noOfPersons ; i++) System.out.println(i + ": " + personGroup[i].getForename() + " " + personGroup[i].getSurname() + " " + personGroup[i].getAge()) ; // sort the data for (int i = 1 ; i < noOfPersons ; i++) { int j = i ; String s = personGroup[i].getSurname() ; Person p = personGroup[i] ; while ((j > 0) && (personGroup[j - 1].getSurname().compareTo(s) > 0)) { personGroup[j] = personGroup[j - 1] ; j-- ; } personGroup[j] = p ; } System.out.println() ; // display the sorted data for (int i = 0 ; i < noOfPersons ; i++) System.out.println(i + ": " + personGroup[i].getForename() + " " + personGroup[i].getSurname() + " " + personGroup[i].getAge()) ; // search for a specified surname BasicIo.prompt("Type the surname to be searched for: ") ; String surname = BasicIo.readString() ; // linear search /* int i = 0 ; boolean matchSurname = false ; while (i < noOfPersons) { int result = personGroup[i].getSurname().compareTo(surname) ; if (result == 0) { matchSurname = true ; break ; } else if (result > 0) break ; i++ ; } if (matchSurname) System.out.println("found at position " + i) ; else System.out.println("no such person") ; */ // binary search int i = -1 ; int j = noOfPersons ; int k = 0 ; boolean matchSurname = false ; while (((i + 1) < j) && (!matchSurname)) { k = (i + j) / 2 ; int result = personGroup[k].getSurname().compareTo(surname) ; if (result == 0) matchSurname = true ; else if (result < 0) i = k ; else // i.e. result > 0 j = k ; } if (matchSurname) System.out.println("found at position " + k) ; else System.out.println("no such person") ; } // end of method main } // end of class Chapter9n4
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -