Linear search and Binary search




In the last post we had discussed about the algorithm for linear and binary search

In this post we have made a program in which we have two functions one for linear search and other for binary search.

You can look at the code and understand the implementation in C language

Program for linear search and binary search in C language :



#include <stdio.h>
void linearSearch(int array[], int ele)
{
    // traverse using for loop
    for (int i = 0; i < 8; i++)
    {
        if (array[i] == ele)
        {
            printf("element %d found at index %d\n", ele, i);
            return;
        }
    }
    printf("element %d NOT found\n", ele);
}

void binarySearch(int array[], int ele)
{
    int ub = 7;
    int lb = 0;
    int mid = (lb + ub) / 2;
    while (ub >= lb)
    {
        if (array[mid] == ele)
        {
            printf("element %d found at index %d\n", ele, mid);
            return; // to terminate the loop and exit
        }
        else if (array[mid] < ele)
        {
            lb = mid + 1;
            mid = (lb + ub) / 2;
        }
        else if (array[mid] > ele)
        {
            ub = mid - 1;
            mid = (lb + ub) / 2;
        }
        if(ub < lb){
           printf("element %d NOT found\n", ele); 
        }
    }
}
int main(int argc, char const *argv[])
{
    int arr[] = {3, 2, 5, 1, 6, 8, 4, 9};
    int sortedArr[] = {1, 3, 4, 5, 6, 8, 10, 12};
    int element = 6;
    linearSearch(arr, element);
    element = 7;
    linearSearch(arr, element);
    element = 8;
    binarySearch(sortedArr, element);
    element = 2;
    binarySearch(sortedArr, element);
    // printf("\ncomplete!");
    return 0;
}

So this was the code for implementing the search algorithms. I hope you have understood the code. For any doubts write down in the comments we will answer you ASAP. 

Till then #KeepLearningKeepGrowing.