Binary search – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sun, 25 Apr 2021 06:27:52 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg Binary search – Programmerbay https://programmerbay.com 32 32 Difference Between Linear Search And Binary Search in Tabular Form https://programmerbay.com/difference-between-linear-search-and-binary-search/ https://programmerbay.com/difference-between-linear-search-and-binary-search/#respond Wed, 12 Aug 2020 16:52:58 +0000 https://www.programmerbay.com/?p=2568 Searching algorithms are used to check whether an element exists in the given data structure or not. And likewise, if it is found then relevant operation would be performed on it.

Based on the traversing mechanism, it can be classified into two categories.  Linear Search and Binary Search. 

Binary search vs linear search

Linear Search iterates over elements sequentially to find data stored in the given list, whereas, Binary Search randomly compares the middle element of a list with desired data on each iteration and uses divide and conquer approach.

Difference between Binary Search and Linear Search in Tabular form

BasisLinear SearchBinary Search
AlgorithmIt sequentially searches an element by comparing each element stored in the given list from start to endIt is based on divide and conquer rule. It searches position of a target value within a sorted array
Sorted ListIt is not mandatory to have a sorted list It is mandatory to have a list to be sorted
WorkingThe algorithm works by checking each and every element sequentially at a time until a match is foundThe algorithm works by slicing a sorted list into two halves from the middle on each iteration until position of a target value is found
ImplementationIt can implemented on data structures which allow traversal atleast in one way such as arrays and Linked list It can be implemented on data structures that supports two way traversal only
Simplicity and ComplexitySimpler and less complex than Binary searchMore complex than Linear search
ApproachIt follows sequential approach and is iterative in nature It follows Divide and Conquer rule
Time ComplexityThe time complexity for Linear search is O(n) The time complexity for Binary search is O(log n)
EfficiencyIt is not efficient when it comes to search in large data set It is efficient as compared to Linear Search
Best CaseThe best case occurs when a matching element is found at first position of an arrayThe best case occurs when a matching element is found at first split which is the middle element of an array
Also KnownIt is also known as Sequential SearchIt is also known as half-interval search and logarithmic search

Linear Search or Sequential Search

Linear search, also refereed as Sequential search is a simple technique to search an element in a list or data structure.

It works by sequentially comparing desired element with other elements stored in the given list, until a match is found. In simple other words, it searches an element by iterating over items one by one from start to end. 

It is one of the simplest technique to search an element, but also costly and slower when it comes to work with a large datasets.

Further, it is considered to be practical when element list size is small or performing a single search on unsorted list. It is not efficient as Binary Search. 

Linear Search 1These are the following steps in the manner in which linear search works:

  1.  Get search element as input from the user
  2. Start Comparing the search element with first element of the given list
  3. If a match is found, print ‘element is found’ and terminate the method
  4. Otherwise, compare the search element with the next upcoming element of the list.
  5. Repeat third and fourth steps until a match is found .
  6. Compare last element of the list with search element, if still no match is found, print “element doesn’t exist” and terminate the method.

Important Points to Remember in Case of Linear Search

– An algorithm that sequentially searches an element in the given list, without skipping any item
– It follows sequential approach to find an element
– It applies on sequence containers ( that can be accessed sequentially ) such as array,deque, linked list and vector
– It is not mandatory to have an ordered element list, therefore, it is easy to use
– In linear search, performance is calculated using equality comparisons
– O(n) is the worst case scenario in linear search which happens when a searching element is the last element in the list
– O(1) is the best case scenario in linear search which happens when a searching element is matched at very first comparison in the list
– O(n) (n represents number of elements in input range) is the time complexity of linear search.

Binary Search 

It is a more efficient method than Linear search and one of the popular ones for searching an element stored in a data structure. 

It is mandatory to a list to be sorted.

Based on divide and conquer mechanism, it slices a list into two halves by dividing it from the middle on each iteration.

The middle item is then compared with the searching element if it is greater than the current one ( middle element)  then the further search would be performed on right sub-array, discarding left one. The same process would be followed again until a match is not found.

 

The first step is mandatory, List should be sorted,

search 1

Now, Slice it from the middle into two sub-array  ( In this case, Index 3 is at middle) and compare the element at that position with searching element which is 25

search 2

Since, 25 > 15

Therefore, we moved to the right as greater numbers are lying towards the right by Discarding Left ones

search 3

search 4

Important Points to Remember in Case of Binary Search

– An algorithm that searches an element by comparing middle or target value, calculated by dividing the given sorted list in two halves on each iteration
– It follows divide and conquer rule
– It applies on data structures where two-way traversal is applicable such as array
– It is not mandatory to have an ordered element list, therefore, it is a bit complex
– In linear search, performance is calculated using ordering comparisons
– O(Log n) is the worst case scenario in binary search
– O(1) is the best case scenario in binary search which happens when a searching element is matched at very first middle element in the list
– O(log n) (n represents number of elements in input range) is the time complexity of binary search

Important Differences

  1. A linear search checks single data 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.
  2. 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.
  3. In a linear search, the elements are accessed sequentially, whereas; in binary search, the elements are accessed randomly.
  4. There is no need to sort data in a linear search while in binary search, the elements need to sort first.
  5. 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.
  6. Example:

C++ Program to implement Linear Search

#include <iostream>

using namespace std;

int main ()
{

  int searchElement, arrList[5] = { 10, 43, 3, 21, 5 };
  int flag = 0;
  cout << "Enter value to search  : ";
  cin >> searchElement;
  for (int i = 0; i < 5; i++)
    if (arrList[i] == searchElement)
      {
  cout << "\n Element is Found";
  flag = 1;
  break;
      }

  if (flag == 0)
    cout << "Element does not exist!" ;
    return 0;
}

Output:

Enter value to search : 21
Element is Found

C++ program to implement Binary Search –

#include <iostream>

using namespace std;

int main() {

int f,l,mid,n,s,arr[10];
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;
}

Output:

enter no. of elements : 5
Provide the values : 23
4
54
3
23
enter value to search : 54
element found

]]>
https://programmerbay.com/difference-between-linear-search-and-binary-search/feed/ 0
C Program to search an element using Binary Search https://programmerbay.com/program-to-search-an-element-using-binary-search/ https://programmerbay.com/program-to-search-an-element-using-binary-search/#respond Fri, 12 Jun 2020 16:20:56 +0000 https://www.programmerbay.com/?p=2921 The program simply searches an element in the given array. There are two searching algorithms, linear search and binary search to achieve this functionality.

Binary Search

Binary search is a searching algorithm to find the given value within an array. This algorithm only works if the given array is already sorted. So that it canĀ figure out whether the given element exists or not.

It works by dividing a list into two halves and compare the middle element with the desired value.

If the value doesn’t match, the half in which the desired value can’t be present gets eliminated and again the remaining one is split down from the middle and that middle term again compared. It is repeated until a match is not found.

It requires O(log n) running time to search an element in the worst case scenario. It is also known as half-interval search.

Pseudocode

first=0
last=Array.Length -1 
WHILE first<= last
mid= (first+last)/2
IF arr[mid]== element 
return mid
ELSE IF arr[mid]> element
last=mid-1
ELSE
first=mid+1
END IF
END IF
END WHILE

C program to search an element using binary search

#include<stdio.h>
#include<math.h>
int Binary_Search(int arr[], int element,int size)
{
int pos=-1,mid,first,last;
first=0;
last=size-1;
while(first<= last)
{
mid= (first+last)/2;
if(arr[mid]== element)
{
pos = mid;
break;
}
else if(arr[mid]>element)
last=mid-1;
else
first=mid+1;
}
return pos; 
}

int main()
{
int arr[]={1,2,3,4,5}; 
int i,pos,element;
printf("\n Please enter an element to search in list: ");
scanf("%d",&element);
pos =Binary_Search(arr,element,5);
if(pos!=-1)
printf("\n your element found at : %d position and the number was %d ", pos+1,arr[pos]);
else
printf("element is not found");
return 0;
}

 

Output:

binary search

How does Binary search work ?

binary search working

 

]]>
https://programmerbay.com/program-to-search-an-element-using-binary-search/feed/ 0