- A linear search checks one thing at any given moment, without bouncing to any other thing. Conversely, binary search chops down your search to half when you locate the center of a sorted list.
- Time taken to search components continue to increase as the number of components is increased while searching through the linear process. Yet, binary search packs the searching time frame by separating the entire array into two halves.
- In a linear search, the elements are accessed sequentially, whereas; in binary search, the elements are accessed randomly.
- There is no need to sort data in a linear search while in binary search, the elements need to sort first.
- Linear search is considered to be effective for the small amount of data, whereas; binary search can efficiently handle large as well as small amounts of data.
- Example:

Linear search-

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
#include<iostream.h> Int main() {int n,s,arr[100]; Cout<<”enter no. of elements”; Cin>>n; For(int c=0;c<n;c++) Cin>>arr[c]; Cout<<”enter value to search”; Cin>>s; For(int i=0;i<n;i++) If(arr[i]==s) {cout<<”element found”; Break; } Return 0; } |

Binary search-

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
#include<iostream.h> Int main() {int f,l,mid,n,s,arr[100]; Cout<<”enter no. of elements”; Cin>>n; For(int c=0;c<n;c++) Cin>>arr[c]; Cout<<”enter value to search”; Cin>>s; f = 0; l = n - 1; mid = (f+l)/2; while (f <= l) { if (arr[mid] < s) f = mid + 1; else if (arr[mid] == s) { cout<<”element found”; break; } else l = mid - 1; mid = (f + l)/2; } if (f > l) cout<<”not found” return 0; } |