PF Lec13 Searching
PF Lec13 Searching
Dr. Fahad
Searching and Sorting
Topics
• Sequential Search (Linear Search)
• Binary Search
• Bubble Sort
• Insertion Sort
Reading
• Sections 6.6 - 6.8
Common Problems
o Binary search
Searching Arrays: Linear Search
• Linear search
o Compare each element of array with key value
– Start at one end, go to other
02-Jan-24
Example (Linear Search)
void main (){
const int size=10;
int a[size]={ 5,6,1,8,3,7,2,10,9,4};
int searchKey;
cout << "Enter integer search key: ";
cin >> searchKey;
for( k=0; k<size; k++)
if (a[k]==searchKey){
cout<<"The element to be searched is found at index
a["<<k<<"]";
break;
}
If (k==size)
cout<<"The element to be searched is NOT found;
}
Binary Search
Is this fast ?
How Fast is a Binary Search?
• 32 = 25 and 512 = 29
• 8 < 11 < 16 23 < 11 < 24
• 128 < 250 < 256 27 < 250 < 28
A Very Fast Algorithm!
#include <iostream>
using namespace std;
int binarySearch(int array[], int x, int low, int high);
int main() {
int array[] = {3, 4, 5, 6, 7, 8, 9};
int x = 4;
int n = sizeof(array) / sizeof(array[0]);
int result = binarySearch(array, x, 0, n - 1);
if (result == -1)
cout<<"Not found";
else
cout<<"Element is found at index ” << result;
}
The end