Searching
Searching
Searching-
1. Linear Search
2. Binary Search
Linear Search:
Linear Search is the simplest searching algorithm.
It traverses the array sequentially to locate the required element.
It searches for an element by comparing it with each element of the array one by one.
So, it is also called as Sequential Search.
Begin with the leftmost element of arr[] and one by one compare x with each element.
If x matches with an element then return the index.
If x does not match with any of the elements then return -1.
Linear Search Example-
Consider-
We are given the following linear array.
Element 15 has to be searched in it using Linear Search Algorithm.
Now,
Linear Search algorithm compares element 15 with all the elements of the array one
by one.
It continues searching until either the element 15 is found or all the elements are
searched.
Step-01:
Step-02:
Step-03:
Step-04:
Step-05:
Example2:
Example3:
Time Complexity Analysis-
Best case-
Worst Case-
Thus, we have-
Linear Search is less efficient when compared with other algorithms like Binary Search &
Hash tables.
The other algorithms allow significantly faster searching.
Implementing Linear Search in C
#include<stdio.h>
int main()
int a[20],i,x,n;
scanf("%d",&n);
for(i=0;i<n;++i)
scanf("%d",&a[i]);
scanf("%d",&x);
for(i=0;i<n;++i)
if(a[i]==x)
break;
if(i<n)
else
return 0;
}
Binary Search-
if (x == arr[mid])
return mid
low = mid + 1
high = mid - 1
Binary Search Example-
Consider-
We are given the following sorted linear array.
Element 15 has to be searched in it using Binary Search Algorithm.
Step-01:
Step-02:
Since a[mid] = 20 > 15, so we take end = mid – 1 = 3 – 1 = 2 whereas beg remains
unchanged.
We compute location of the middle element as-
mid
= (beg + end) / 2
= (0 + 2) / 2
=1
Here, a[mid] = a[1] = 10 ≠ 15 and beg < end.
So, we start next iteration.
Step-03:
Since a[mid] = 10 < 15, so we take beg = mid + 1 = 1 + 1 = 2 whereas end remains
unchanged.
We compute location of the middle element as-
mid
= (beg + end) / 2
= (2 + 2) / 2
=2
Here, a[mid] = a[2] = 15 which matches to the element being searched.
So, our search terminates in success and index 2 is returned.
Example2:
Time Complexity Analysis-
Thus, we have-
// Binary Search in C
#include <stdio.h>
if (array[mid] == x)
return mid;
if (array[mid] < x)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main(void) {
int array[] = {3, 4, 5, 6, 7, 8, 9};
int n = sizeof(array) / sizeof(array[0]);
int x = 4;
int result = binarySearch(array, x, 0, n - 1);
if (result == -1)
printf("Not found");
else
printf("Element is found at index %d", result);
return 0;
}