Java Reference
In-Depth Information
74
// repeatedly input an integer; -1 terminates the program
75
while (searchInt != -1 )
76
{
77
// perform search
78
int location = binarySearch(data, searchInt);
79
80
if (location == -1 ) // not found
81
System.out.printf( "%d was not found%n%n" , searchInt);
82
else // found
83
System.out.printf( "%d was found in position %d%n%n" ,
84
searchInt, location);
85
86
// get input from user
87
System.out.print( "Please enter an integer value (-1 to quit): " );
88
searchInt = input.nextInt();
89
}
90
} // end main
91
} // end class BinarySearchTest
[13, 18, 29, 36, 42, 47, 56, 57, 63, 68, 80, 81, 82, 88, 88]
Please enter an integer value (-1 to quit): 18
13 18 29 36 42 47 56 57 63 68 80 81 82 88 88
*
13 18 29 36 42 47 56
*
13 18 29
*
18 was found in position 1
Please enter an integer value (-1 to quit): 82
13 18 29 36 42 47 56 57 63 68 80 81 82 88 88
*
63 68 80 81 82 88 88
*
82 88 88
*
82
*
82 was found in position 12
Please enter an integer value (-1 to quit): 69
13 18 29 36 42 47 56 57 63 68 80 81 82 88 88
*
63 68 80 81 82 88 88
*
63 68 80
*
80
*
69 was not found
Please enter an integer value (-1 to quit): -1
Fig. 19.3 | Use binary search to locate an item in an array (the * in the output marks the middle
element). (Part 3 of 3.)
Search WWH ::




Custom Search