Searching in c++
Searching in c++
Searching in c++
• Involves going through a list step by step and comparing each element with the target item
to find its location.
Compare the search element with the first element in the list.
Used to find the given elements from the sorted array by continuously halving the
array and then searching specified elements from a half array.
Step 3 - Compare the search element with the middle element in the sorted list.
Step 4 - If both are matched, then display "Given element is found!!!" and terminate the function.
Step 5 - If both are not matched, then check whether the search element is smaller or larger than the middle element.
Step 6 - If the search element is smaller than middle element, repeat steps 2, 3, 4 and 5 for the left sublist of the middle element.
Step 7 - If the search element is larger than middle element, repeat steps 2, 3, 4 and 5 for the right sublist of the middle element.
Step 8 - Repeat the same process until we find the search element in the list or until sublist contains only one element.
Step 9 - If that element also doesn't match with the search element, then display "Element is not found in the list!!!" and terminate the
function.
Program
#include<iostream> int main()
{ int start=0;
{ int searchN=15;
return mid; {
left=mid+1; }
else
else
{
right=mid-1;
cout<<"present at index "<<output;
} return -1; }
}}
By recursion
#include<iostream>
{ int length=sizeof(arr)/sizeof(arr[0]);
int mid=(right+left)/2; {
return mid; }
return binaryRecu(arr,mid+1,right,target); {
else cout<<"Found";
return binaryRecu(arr,left,mid-1,target); }
}
Advantages
Works faster than linear search.
It is a simple algorithm.
Elements are searched in a sequential manner (one Elements are searched using the divide-and-
by one). conquer approach.
The elements in the array can be in random order. Elements in the array need to be in sorted order.
Does not Efficient for larger arrays. Efficient for larger arrays.
The worst-case time complexity is O(n). The worst case time complexity is O(log n).
Thank You