1
+ import java .util .Scanner ;
2
+ import java .util .ArrayList ;
3
+
4
+ public class NameFinder {
5
+ /* Finds index of string in vector of strings, else -1.
6
+ Searches only with index range low to high
7
+ Note: Upper/lower case characters matter
8
+ */
9
+ public static int findMatch (ArrayList <String > stringList , String itemMatch ,
10
+ int lowVal , int highVal , String indentAmt ) { // indentAmt used for print debug
11
+ int midVal ; // Midpoint of low and high values
12
+ int itemPos ; // Position where item found, -1 if not found
13
+ int rangeSize ; // Remaining range of values to search for match
14
+
15
+ System .out .println (indentAmt + "Find() range " + lowVal + " " + highVal );
16
+ rangeSize = (highVal - lowVal ) + 1 ;
17
+ midVal = (highVal + lowVal ) / 2 ;
18
+
19
+ if (itemMatch .equals (stringList .get (midVal ))) { // Base case 1: item found at midVal position
20
+ System .out .println (indentAmt + "Found person." );
21
+ itemPos = midVal ;
22
+ }
23
+ else if (rangeSize == 1 ) { // Base case 2: match not found
24
+ System .out .println (indentAmt + "Person not found." );
25
+ itemPos = -1 ;
26
+ }
27
+ else { // Recursive case: search lower or upper half
28
+ if (itemMatch .compareTo (stringList .get (midVal )) < 0 ) { // Search lower half, recursive call
29
+ System .out .println (indentAmt + "Searching lower half." );
30
+ itemPos = findMatch (stringList , itemMatch , lowVal , midVal , indentAmt + " " );
31
+ }
32
+ else { // Search upper half, recursive call
33
+ System .out .println (indentAmt + "Searching upper half." );
34
+ itemPos = findMatch (stringList , itemMatch , midVal + 1 , highVal , indentAmt + " " );
35
+ }
36
+ }
37
+
38
+ System .out .println (indentAmt + "Returning pos = " + itemPos + "." );
39
+ return itemPos ;
40
+ }
41
+
42
+ public static void main (String [] args ) {
43
+ Scanner scnr = new Scanner (System .in );
44
+ ArrayList <String > attendeesList = new ArrayList <String >(); // List of attendees
45
+ String attendeeName ; // Name of attendee to match
46
+ int matchPos ; // Matched position in attendee list
47
+
48
+ // Omitting part of program that adds attendees
49
+ // Instead, we insert some sample attendees in sorted order
50
+ attendeesList .add ("Adams, Mary" );
51
+ attendeesList .add ("Carver, Michael" );
52
+ attendeesList .add ("Domer, Hugo" );
53
+ attendeesList .add ("Fredericks, Carlos" );
54
+ attendeesList .add ("Li, Jie" );
55
+
56
+ // Prompt user to enter a name to find
57
+ System .out .print ("Enter person's name: Last, First: " );
58
+ attendeeName = scnr .nextLine (); // Use nextLine() to allow space in name
59
+
60
+ // Call function to match name, output results
61
+ matchPos = findMatch (attendeesList , attendeeName , 0 , attendeesList .size () - 1 , " " );
62
+ if (matchPos >= 0 ) {
63
+ System .out .println ("Found at position " + matchPos + "." );
64
+ }
65
+ else {
66
+ System .out .println ("Not found." );
67
+ }
68
+ }
69
+ }
0 commit comments