Mechatronics geek blog

Saturday, April 27, 2019

Searching Algorithm

Searching Algorithms:
---------------------------
1-Sequential Search
2- Binary Search
----------------------------------------------------------
1- Sequential Search:
    -Searching in an array of N.
    -Time complexity: O(N)

int sequentialSearch (int * arr, int size, int data)
{
       int index= -1;
       int i;
       for(i=0;i<size;i++)
       {
          if(arr[i] == data)
          {
           return i; /* Once the data is found return the index and exit the function*/
           }
         }
       return index;
}

===================================================================
2- Binary Search: is applied on "Sorted data" 
    - Data must be sorted.
    - Time Complexity: O(log N)

int binarySearch(int*arr, int size ; int data)
{
int low=0;
int high=size-1;
while(low<=high)
{
mid=(low+high)/2;
if(data>arr[mid])
{
low=mid+1
}
else if(data<arr[mid])
{
high=mid-1;
}
else
{
return mid;
}
return -1;
}

---------------------------------------------------
The same Function using Recursion:

int recBinarySearch(int*arr,int low , int high,int data)
{
int mid=(high+low)/2;
if(low>highh)
{
return -1;
}
if(arr[mid] < data)
{
  low=mid+1;
return recBinarySearch(arr,low,high,data);
}
else if (arr[mid] > data)
{
  high=mid-1;
return recBinarySearch(arr,low,high,data);
}
else
return mid;
}
============================================================










0 comments:

Post a Comment