linear 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 linear 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 Find an Element Using Linear Search https://programmerbay.com/program-to-search-an-element-using-linear-search/ https://programmerbay.com/program-to-search-an-element-using-linear-search/#respond Fri, 12 Jun 2020 09:49:18 +0000 https://www.programmerbay.com/?p=2912 The program simply searches an element in the given array and prints it on output screen using linear search searching technique.

Linear Search

Linear search is a searching technique to check whether an element is present in the given list or not.

It checks for the user’s input element existence in the given list by sequentially comparing all the elements of the array one by one, if a match is found then it would return the position of the desired element.

It requires O(n) time to search a given element in the worst case scenario. It is also known as Sequential Search.

Pseudocode

FOR position=0 to Array.length
IF Array[position] = ElementToSearch
return position+1
END IF 
END FOR

C program to search an element in an array using Linear search

/**

C program to search an element using Linear Search
**/

#include<stdio.h>
#define size 5

int linearSearch (int arr[], int element)
{
  int i, position = -1;
  for (i = 0; i < size; i++)
    {
      if (element == arr[i])
  {
    position = i;
    break;
  }
    }
  return position;
}

int main ()
{
  int arr[size], element;
  int i, position;
  printf ("\nPlease enter 5 elements : ");
  for (i = 0; i < size; i++)
    {
      scanf ("%d", &arr[i]);
    }
  printf ("\n Please enter an element to search in list: ");
  scanf ("%d", &element);
  position = linearSearch (arr, element);

  if (position != -1)
    printf ("\n your element found at : %d position and the number was %d ",
      position + 1, arr[position]);
  else
    printf ("element is not found");

  return 0;
}

Output:

When element is exist

linear search

When element is not exist

linear search 2

How does Linear Search work?

linear search working

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