Data
Data
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.
42
99
51
17
92
Main routine:
1. Initialize array
2 P
2.
Promptt ffor kkey
3 Call search
3.
4. Output
p results
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;;
}
Linear Search:
1. Traverse array
2. Look for value
3 If end reached
3.
reached,
value not present
if (A[LB] = = value)
return LB;
else
l
return LinearSearch(A, value, LB+1, UB);
}
Runtime of algorithms:
O d notation
Order
i
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.
10 11 45
k < 50
key
mid
id
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
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
}
Output
p Routines
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