array
sIn this section, we use the built-in C++ Standard Library sort
function to arrange the elements in an array
into ascending order and the built-in binary_search
function to determine whether a value is in the array
.
Sorting data—placing it into ascending or descending order—is one of the most important computing applications. A bank sorts all checks by account number so that it can prepare individual bank statements at the end of each month. Telephone companies sort their phone directories by last name—and within all entries with the same last name, sort those by first name—to make it easy to find phone numbers. Virtually every organization must sort some data and, in many cases, massive amounts of it. Sorting data is an intriguing problem that has attracted some of the most intense research efforts in the field of computer science. In Chapter 20, we investigate and implement several sorting schemes, discuss their performance and introduce Big O (pronounced “Big Oh”) notation for characterizing how hard each scheme works to accomplish its task.
Often it may be necessary to determine whether an array
contains a value that matches a certain key value. The process of finding a particular element of an array
is called searching. In Chapter 20, we investigate and implement two search algorithms—the simple but slow linear search for searching an unordered array
and the more complex but much faster binary search for searching an ordered array
.
sort
and binary_search
Figure 7.15 begins by creating an unsorted array
of string
s (lines 12–13) and displaying the contents of the array
(lines 17–19). Next, line 21 uses C++ Standard Library function sort
to sort the elements of the array
colors
into ascending order. The sort
function’s arguments specify the range of elements that should be sorted—in this case, the entire array
. The arguments colors.begin()
and colors.end()
represent the array
’s beginning and end, respectively—we’ll discuss the complete details of begin
and end
in Chapter 15. As you’ll see, function sort
can be used to sort the elements of several different types of data structures. Lines 25–27 display the contents of the sorted array
.
Lines 30 and 35 use binary_search
to determine whether a value is in the array
. The sequence of values first must be sorted in ascending order—binary_search
does not verify this for you. The function’s first two arguments represent the range of elements to search and the third is the search key—the value to locate in the array
. The function returns a bool
indicating whether the value was found. In Chapter 16, we’ll use the C++ Standard function find
to obtain the location of a search key in an array
.