Home Practices Page 2 - Basic Array Searching in C++

# Sequential Search - Practices

Searching arrays for a particular value is a common activity that any programmer should know how to do. Bryan Roth discusses two basic searching methods, sequential and binary, and shows how to code them in C++.

By: Bryan Roth
Rating:  / 47
December 27, 2004

SEARCH DEV SHED

TOOLS YOU CAN USE

The sequential search is best used if the array you are searching is unsorted. This method of searching is usually used on small arrays of less than 16 elements. We start the sequential search by first declaring a target to be found. The search initiates at the beginning of the array until it finds the target.

In the following example we will find a target value of 23 within a one dimensional array. At index 0, 32 is not equal to 23 so we proceed on to the next element.

 a[0] a[1] a[2] a[3] a[4] 32 431 -34 23 12

At index 1, 431 is not equal to 23 so we proceed.

 a[0] a[1] a[2] a[3] a[4] 32 431 -34 23 12

At index 2, -34 is not equal to 23 so we proceed.

 a[0] a[1] a[2] a[3] a[4] 32 431 -34 23 12

Finally at index 3, 23 is equal to 23 and we have found our target.

 a[0] a[1] a[2] a[3] a[4] 32 431 -34 23 12

Now we will implement this example of a sequential search into C++ code. The program below asks the user for a target to be found, then uses a for loop to analyze each element of the array. If the array element is equal to the target it will display that the target was found. Whenever a target is found the variable “flag” will be incremented by 1. At the end of the program if the variable “flag” is less than one, then the target was obviously not found.

#include <iostream>
using namespace std;

int main()
{
const int arraySize = 5;
double target;
int array[arraySize] = {32, 431, -34, 23, 12};
int flag;

// flag is used to log how many times the target is encountered.

flag = 0;

cout << "Enter a target to be found: ";
cin >> target;

for(int cntr = 0; cntr < arraySize; cntr++)
{
if(array[cntr] == target)
{
cout << "Target found in array index " << cntr << "."
<< endl;

flag += 1;
}
}

// Test to see if target was found.

if(flag < 1)
{
}

return 0;
}

The sequential search does have a pitfall. It is very slow and its performance rating is low. If a person had an array of one million elements, that would mean there could be up to one million comparisons, and that takes time! The sequential search method would be advisable to use only if the array you were searching was unsorted and small.

 >>> More Practices Articles          >>> More By Bryan Roth