DEV Community

Cover image for Linear search and Binary Search  for beginner-01.
Amitanandan
Amitanandan

Posted on

Linear search and Binary Search for beginner-01.

hey guys hope you are doing well .So here I will explain two search operations in simple way. I will try to explain this with some examples.After reading this article you will be able to understand their differences and why binary search is better than linear search so lets start!
LINEAR SEARCH-
consider and array={2,3,4,5,6,7},suppose we are searching an element 2.how we will do?here is simple code to make u understand all despite of any coding background(note that I have not used any particular language just writing down simply)
int target=2
int arr[]={2,3,4,5,6,7}
for(int i=0;i<arraylength-1;i++)
if(arr[i]=target) output the element i or u can make output the target with element according to your wish.
BEST CASES:-
now we will see how much time it would take like the best time it would take and the worst time it would take to complete the whole algorithm.
so if the target is 2(or the first element) then it will take no time that is constant you will ask how? lets find the answer.Okay suppose the same array we make input of several element array={2,3,4,5,6,7,8,9,10}now search for 2 through for loop,in the first check itself it will give the answer so with increase of size the answer it will give only in the first check so how would the graph look like!just think. In the y-axis is time and x-axis is the size of array.This is your task.
WORST CASE:-
worst case is nothing but the time your algorithm takes to make the check on last element. In this case it will depend on the size of the array? you will say how? so before that just think. we have to discussed two examples right! so we will say the 1eg(2,3,4,5,6,7) and 2eg(2,3,4,5,6,7,8,9,10)
in 1eg if we make the search of 7 how much check it will make to find our answers obviously it will check 6 times or we cans say the length of the array times. And in 2eg how much check it will make 9 times. Did u get? okay some of u may have get but some may not . okay carefully look the algorithm it says when it will find the element it will make output of the element index.so at first it will check with 2 and again it will check with 3 and again for 4 and then 5 and so on until it finds our target, so how much check it will make obviously the size of array. Then how will the plot between size of array and time(in this case u just compare with time as no of checks as if many checks are there the algorithm(set of codes)will take more time and if it makes less checks then it will take less time) look like? Think! I will answer in next post. Thank you for bearing your eyes to see this post. Hope you like it.

Top comments (0)