Responsive Advertisement

Binary Search

Binary Search is one of the complex structures in the programming language. In this tutorial, I am going to perform the binary search tree using the c programming language. Binary Search is a complex and having algorithm that's the reason it comes under the Data Structure.

The main concept behind the Binary Search is we take the data and search in the given array. For that we have to assign the value of lower and higher mean the value at index 0 and the value at index n (last index) we add both values and then divide by 2. then we get the mean value, the same way we implement the process.

Binary Search 


The time complexity of the Binary Search is

1. In Best case is Big O(1)


The code and output is here so you can copy and then run in your own computer and laptop


Code:-

#include <iostream>

using namespace std;


int binarySearch(int arr[], int num, int less, int greater) {

  

  while (less <= greater) {

    int mid = less + (greater - less) / 2;


    if (arr[mid] == num)

      return mid;


    if (arr[mid] < num)

      less = mid + 1;


    else

      greater = mid - 1;

  }


  return -1;

}


int main(void) {

  int arr[] = {50,51,52,53,54,55,56};

  int num = 55;

  int n = sizeof(arr) / sizeof(arr[0]);

  int result = binarySearch(arr, num, 0, n - 1);

  if (result == -1)

    printf("The number are not found in array");

  else

    printf("The value is present in place %d is %d", result);

}

Output:-

The value is present in place 5 is 0

--------------------------------


So Try to run the above-given program in your own system and comment bellow whether you get the correct output or not. Keep visiting to the Red code .

Thanks-




Post a Comment

0 Comments