The binary search algorithm is easy to understand and to implement. Nevertheless, with a run order of O(log n), it is an efficient algorithm for searching arrays for a given element. The goal is to locate a specific value quickly (called the key) in an array or determine that it isn't there. A run order of O(log n) means that a large increase in the data size results in a relatively small increase in the runtime. The one drawback of binary search is that it only operates on a sorted array, making it dependent on the sorting algorithm. Coupled with selection sort, binary search is useful for small arrays or arrays whose contents change infrequently. The next chapter introduces a more efficient sorting algorithm that greatly extends the usefulness of binary search.
![]() |
![]() |
![]() |
![]() |
![]() |
| (a) | (b) | (c) | (d) | (e) |
| Driver | Binary Search |
|---|---|
#include <iostream>
using namespace std;
void ssort(char* data, int size);
int binsearch(char key, char* data, int size);
int main()
{
char data[] = { 'S','E','E','T','H','E','Q','U',
'I','C','K','R','E','D','F','O','X' };
int size = sizeof(data) / sizeof(char);
|
|
Searching for a particular value in an array of fundamental data (e.g., characters or integers) has limited value, but it becomes more useful when the array elements are objects. A common practice is to use one or more fields as the key to sort the array. A program searches the array for a given key and, if it finds a matching object, can access all the data associated with that key (i.e., stored in the object). This operation is called an associative search.
#include <iostream>
using namespace std;
struct student
{
const char* name;
int id;
double gpa;
};
void ssort(student* data, int size);
int binsearch(int key, student* data, int size);
int main()
{
student students[] = {
{ "Dilbert", 123, 3.5 },
{ "Wally", 456, 2.0 },
{ "Alice", 987, 3.9 },
{ "Asok", 730, 3.8 },
{ "Catbert", 501, 3.0 },
{ "Pointy Haired Boss", 666, 1.0 },
{ "Dogbert", 111, 4.0 }
};
int size = sizeof(students) / sizeof(student);
|
#include <iostream>
#include <cstring>
using namespace std;
struct student
{
const char* name;
int id;
double gpa;
};
void ssort(student* data, int size);
int binsearch(char* key, student* data, int size);
int main()
{
student students[] = {
{ "Dilbert", 123, 3.5 },
{ "Wally", 456, 2.0 },
{ "Alice", 987, 3.9 },
{ "Asok", 730, 3.8 },
{ "Catbert", 501, 3.0 },
{ "Pointy Haired Boss", 666, 1.0 },
{ "Dogbert", 111, 4.0 }
};
int size = sizeof(students) / sizeof(student);
|
Programmers must tailor each version of the ssort and binsearch function for a specific key data type. Programmers can generalize the functions with void pointers, but it is awkward. C++ provides a more flexible, easier-to-use solution based on templates. The next chapter describes void pointers and Chapter 13 covers templates.