Java Reference
In-Depth Information
System.out.printf("\nThe sorted names and IDs are\n\n");
for (int h = 0; h < MaxNames; h++)
System.out.printf("%-20s %d\n", name[h], id[h]);
} //end main
// parallelSort goes here
} //end class ParallelSort
When Program P1.4 was run, it produced the following output:
The sorted names and IDs are
Charles, Kandice 4455
Graham, Ariel 3050
Graham, Ashleigh 5000
Greaves, Sherrelle 6050
Perrott, Chloe 2795
Reyes, Aaliyah 6669
Reyes, Ayanna 5464
Seecharan, Anella 7824
We note, in passing, that if we have several sets of related items to process, storing each set in a separate array
would not be the best way to proceed. It would be better to group the items in a class and work with the group as we
would a single item. We'll show you how to do this in Section 2.14.
1.6 Binary Search
Binary search
is a fast method for searching a list of items for a given one,
providing the list is sorted
(either ascending
or descending). To illustrate the method, consider a list of 13 numbers, sorted in ascending order and stored in an
array
num[0..12]
.
Suppose we want to search for
66
. The search proceeds as follows:
1.
We find the middle item in the list. This is
56
in position
6
. We compare
66
with
56
. Since
66
is bigger, we know that if
66
is in the list at all, it
must
be
after
position
6
, since the numbers
are in ascending order. In our next step, we confine our search to locations
7
to
12
.
2.
We find the middle item from locations
7
to
12
. In this case, we can choose either item
9
or
item
10
. The algorithm we will write will choose item
9
, that is,
78
.
3.
We compare
66
with
78
. Since
66
is smaller, we know that if
66
is in the list at all, it
must
be
before
position
9
, since the numbers are in ascending order. In our next step, we confine
our search to locations
7
to
8
.
4.
We find the middle item from locations
7
to
8
. In this case, we can choose either item
7
or
item
8
. The algorithm we will write will choose item
7
, that is,
66
.
5.
We compare
66
with
66
. Since they are the same, our search ends successfully, finding the
required item in position
7
.
Search WWH ::
Custom Search