0% found this document useful (0 votes)
36 views

Data

Searching an array involves comparing elements to a search key. Linear search compares each element sequentially until a match is found, taking O(n) time. Binary search divides the array in half at each step based on comparing the middle element to the key, taking O(log n) time but requiring the array be sorted. Implementations of linear and binary search were tested on sample arrays to find a specified key.

Uploaded by

Vikrant Sahu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Data

Searching an array involves comparing elements to a search key. Linear search compares each element sequentially until a match is found, taking O(n) time. Binary search divides the array in half at each step based on comparing the middle element to the key, taking O(log n) time but requiring the array be sorted. Implementations of linear and binary search were tested on sample arrays to find a specified key.

Uploaded by

Vikrant Sahu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Searching

Searching is the process of looking for a


specific element in an array; for example,
discovering whether a certain score is
included in a list of scores.
scores

Linear Search
The linear search approach compares the key
element, key, with each element in the
array list[].
The method continues to do so until the key
matches an element in the list or the list
s exhausted
h t d without
ith t a match
t h being
b i found.
f
d
If a match is made, the linear search returns
th index
the
i d off the
th element
l
t in
i the
th array that
th t
matches the key.
If no match
t h is
i found,
f
d the
th search
h returns
t
-1.
1

T ti Linear
Testing
Li
Search
S
h
Objective:
Implement and test the linear search method by
creating an array of 10 elements of int type
randomly and then display this array. Prompt
the user to enter a key for testing the linear
search.

Searching Arrays: Linear Search


Search array for a key value
Linear search

Compare each element of array with key value


Useful for small and unsorted arrays
Zoo Atlanta Database - Aardvark ages
13

42

99

51

17

92

Is there a 99-year old Aardvark


at the Atlanta Zoo?

Main routine:
1. Initialize array
2 P
2.
Promptt ffor kkey
3 Call search
3.
4. Output
p results

//Linear search of an array - Zoo


Atlanta Aardvark Age Database
#include <iostream>
int linearSearch(( const int [], int,, int );
int main()
{
const int ARRAYSIZE= 8;
const int NOT_FOUND = -1;
int a[ ARRAYSIZE ] = { 13, 42, 7, 99, 51,3, 7, 92 };

Continuing
Continuing
int searchKey, element;
cout << "Enter integer search key:" << endl;
cin >> searchKey;
element = linearSearch( a, searchKey, ARRAYSIZE);
if ( element !!= NOT_FOUND
NOT FOUND )
cout << "Found value in element " << element ;
else
cout << "Value not found" << endl;
return 0;;
}

int linearSearch( const int array[], int key, int sizeOfArray )


{
for ( int n = 0; n < sizeOfArray; n++ )
if ( array[ n ] == key )
return
t
n;
return NOT
NOT_FOUND;
FOUND;
}

Enter integer search key:


99
Found value in element 3
Enter integer search key:
40
Value not found

Linear Search:
1. Traverse array
2. Look for value
3 If end reached
3.
reached,
value not present

Recursive Procedure for Linear Search


int LinearSearch(int A[ ], int value, int LB, int UB)
{
//int i;
if (LB > UB)
return -1 ;// not found

if (A[LB] = = value)
return LB;
else
l
return LinearSearch(A, value, LB+1, UB);
}

Runtime of algorithms:
O d notation
Order
i

How many steps does it take to do a linear search


of n elements?
Worst case: Element is not in list
Must check every value in the list
Takes n time units
Linear search is order n or O(n)

Binary search
Linear search has linear time
complexity:
Time n if the item is not found
Time n/2
n/2, on average
average, if the item is
found
If the
th array is
i sorted,
t d we can write
it a
faster search

Binary Search
How do we look up a name in a phone
book, or a word in a dictionary?
Look somewhere in the middle
Compare whats there with the thing
youre
you
re looking for
Decide which half of the remaining
entries to look at
Repeat until you find the correct place
This is the binary search algorithm

Binary Search
For binaryy search to work,, the elements in
the array must already be ordered.
Without loss of generality,
generality assume that
the array is in ascending order.
e.g. 2 4 7 10 11 45 50 59 60 66 69 70 79
The binary search first compares the key
with the element in the middle of the
array Consider the following three cases:
array.

Binary Search
Search, cont.
cont
If the key
y is less than the middle element, y
you
only need to search the key in the first half of
y
the array.
If the key is equal to the middle element, the
search ends with a match.
If the key is greater than the middle element,
you only need to search the key in the second
half of the array.

Binary Search, cont.


key = 11
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
list

10 11 45

k < 50
key

mid
id

[0] [1] [2] [3] [4] [5]


2
key > 7

10 11 45

mid
[3] [4] [5]
10 11 45

key = 11

50 59 60 66 69 70 79

mid

Binary
y search,, cont.
Recursive solution binarySearch(key,
y
( y, list,, low,, high):
g )
if low > high
return -1 (failure)
else
find middle index between low and high
if li
list[middle]
t[ iddl ] == key
k return
t
middle
iddl
else if list[middle] < key return result of
binarySearch
y
on elements to the right
g of middle
else return result of
binarySearch on elements to the left of middle

T ti Binary
Testing
Bi
Search
S
h

Objective:
Implement and test the binary search method.
method
The program first creates an array of 10
elements of int type. It displays this array and
then prompts the user to enter a key for testing
binaryy search.

Binary search takes log n time

In binary search, we choose an index that cuts


the remaining portion of the array in half
We repeat this until we either find the value we
are looking for, or we reach a su-barray of size
1
If we start with an array of size n, we can cut it
in half log2n times
Hence, binary
bi
search
h hhas llogarithmic
i h i (l
(log n))
time complexity
For an array off size
i 1000, this
hi is
i 100 times
i
faster than linear search (210 ~= 1000)

Binary Search
Can only be used on sorted arrays
Compares middle element with key
If equal
equal, match found
If key < middle, repeat search
through
g the first half of the arrayy
If key > middle, repeat search
through the last half of the array
30 element array takes at most 5 steps

Binary Search:
11. Initiali
Initializee array
arra
2. Prompt for input
3. Print header
4 C
4.
Call
ll searchh
5. Output results

// Binary
y search of an arrayy
#include <iostream>
#include <iomanip>
using std::setw;
int binarySearch( const int [], int, int, int, int );
void printHeader( int );
void printRow( const int [], int, int, int, int );

int main()
{
const int ARRAYSIZE = 8;
constt int
i t NOTFOUND=
NOTFOUND -1;
1
int ages[ ARRAYSIZE ] = {3, 7, 13, 17, 42, 51, 92, 99}
int key, result;
cout << "Enter a number between 0 and 99: ";
cin >> key;
printHeader( ARRAYSIZE );
result = binarySearch( ages, key, 0, ARRAYSIZE - 1,
ARRAYSIZE );
if ( result != NOTFOUND )
cout << '\n' << key << " found in array element "
<< result << endl;
else
cout << '\n'
\n << key << " not found
found" << endl;
return 0;
}

// Binary search
int binarySearch( const int values[ ],
] int searchKey,
searchKey int low,
low
int high, int size )
1. Calc middle
{
2. Output row
int middle;
while ( low <= high ) {
3. If found, quit
middle = ( low + high ) / 2;
4. If not, divide
printRow( values, low, middle, high, size );
if ( searchKey == values[ middle ] ) // match
array in half
return middle;
else if ( searchKey < values[ middle ] )
high = middle - 1;
// search low end of array
else
low = middle + 1;
// search high end of array
}
return NOTFOUND; // searchKey not found
}

Recursive Procedure for Binary Search


int BinarySearch(int A[ ] , int value, int low, int high)
{
int mid;
if (high < low)
return -1 ;// not found
// mid = low + ((high - low) / 2);
mid=(low + high) / 2 ;
if ((A[mid]
[
] > value))
return BinarySearch(A, value, low, mid-1);
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high);
else
return mid; // found
}

// Print a header for the output


void printHeader( int size )
{
int i;
cout << "\nSubscripts:\n";
for ( i = 0; i < size; i++ )
cout << setw(( 3 ) << i << ' ';;
cout << '\n';
for ( i = 1; i <= 4 * size; i++ )
cout << '-';;
cout << endl;
}

Output
p Routines

// Print one row of output showing the current


// ppart of the arrayy beingg processed.
p
void printRow( const int b[ ], int low, int mid, int high, int size )
{
for ( int i = 0; i < size; i++ )
if ( i < low || i > high )
cout << " ";
else if ( i == mid )
// mark middle value
cout << setw(( 3 ) << b[[ i ] << '*';;
else
cout << setw( 3 ) << b[ i ] << ' ';
cout << endl;
}

Runtime of Binary Search


What is the worst case runtime of a binary
y
search? (Element is not there)
Dividing search space in half each time
Number of steps is closest power of 2 larger
than n
Runtime: O(log2n)
30 elements: 25 = 32, steps = 5
1000 elements: 210 = 1024, steps
p = 10

Conclusion
Linear search has linear time complexity
Binary search has logarithmic time complexity
For large arrays, binary search is far more efficient than
linear search
However, binary search requires that the array be sorted
If the array is sorted, binary search is
100 times faster for an array of size 1000
50 000 times faster for an array of size 1 000 000
This is the kind of speedup that we care about when we
analyze algorithms

You might also like