DSA Searching Techniques.
DSA Searching Techniques.
Searching
Linear Binary
search search
Searching
Searching in data-
structure refers to These set of items
Generally, Searching the process of are in various
means to find or finding a desired forms , such as an
discover something. element in set of Array, Tree, Graph,
items. or Linked-list .
Searching in Array
Linear Binary
search search
Linear Search
It is a very basic and simple search algorithm.
In linear search we search an element in given array by traversing the array from the
starting till the desired element is found.
like : A[ ] = { 10,8,4,7,6,2,5,1,9};
Algorithm
Step 1 - Read the search element from the user.
Step 2 - Compare the search element with the first element in the list.
Step 3 - If both are matched, then display "given element is found!!!" And terminate the function
Step 4 - If both are not matched, then compare search element with the next element in the list.
Step 5 - Repeat steps 3 and 4 until search element is compared with last element in the list.
Step 6 - If last element in the list also doesn't match, then display "element is not found!!!" And terminate the
function.
Example
Code
Int linear_search ( a[ ], LB, UB, item ) // LB= Lower bound, UB= upper bound,
{
int k;
for (k = LB ; k <= UB; K++)
{
if ( a [k] == item )
{
return k ;
}
}
return LB -1;
}
Binary search
Binary search is the search technique that works efficiently on sorted lists.
To search an element into some list using the binary search technique, we must ensure that the
list is sorted.
Binary search follows the divide and conquer approach in which the list is divided into two
halves, and the item is compared with the middle element of the list.
If the match is found then, the location of the middle element is returned. Otherwise, we
search into either of the halves depending upon the result produced through the match.
Algorithm
Step 1 - Start searching data from middle of the list.
.
Code
Int binary_ search ( A[ ], LB, UB, item ) // LB= Lower bound, UB= Upper bound,
{ int low=LB, high=UB;
int mid=(low + high) / 2;
while( (A[mid]!= item) && ( low<=high ) )
{ if( item<A[mid] )
high = mid -1 ;
else
low = mid +1 ;
mid = (low + high ) / 2;
}
if( A[ mid ]= item )
return min ;
else
return LB -1 ;
}
Linear search vs Binary search
Linear search Binary search
1. Data can be in any order. 1. Data should be in sorted order.
2. Multi dimensional array also can 2. Only single dimensional array is
be used. used.
3. Time complexity O(n). 3. Time complexity O ( log (n) ).
4. Not an efficient method to be used 4. Efficient for large inputs also.
if there is a large item.
Visualization
,
Thank you
Thank you