Pps Source 3
Pps Source 3
Digember Kumar
Assistant Professor
Department of Computer Science and Engineering
Input : arr[] = {10, 20, 80, 30, 60, 50, 110, 100, 130, 170}
x = 110;
Output : 6
Element x is present at index 6
Input : arr[] = {10, 20, 80, 30, 60, 50, 110, 100, 130, 170}
x = 175;
Output : -1
Element x is not present in arr[].
Algorithm:
Start from the leftmost element of arr[] and one by one compare x with each element of
arr[].
If x matches with an element, return the index.
If x doesn’t match with any of elements, return -1.
Pseudocode for Linear Search:
a[]: Array of elements
n: no. of elements
x: key
int linearSearchAlgo(a[], x, n){
for(i=0; i<n; i++){
if(a[i] == x)
break;
}
//Element found at index i
if(i < n){
return i;
}
//Element not found
return -1;
}
Advantages of Linear Search Algorithm:
• Linear search can be used irrespective of whether the array is sorted or not.
• It can be used on arrays of any data type.
• Does not require any additional memory.
• It is a well-suited algorithm for small datasets.
In linear search input data need not to be in sorted. In binary search input data need to be in sorted order.
The time complexity of linear search O(n). The time complexity of binary search O(log n).