Write a program to search an element using Binary Search.

Write a program to search an element using Binary Search.

 

#include <stdio.h>

int binarySearch(int array[], int find, int low, int high);

int main(void)

{

  int array[100],size,find;

  printf("Enter size of array:\n");

  scanf("%d",&size);

  printf("Enter-- \n");

  for(int i=0;i <size; i++)

  {

      printf("Element[%d]",i);

      scanf("%d",&array[i]);

  }

 printf("Enter Element to be search:\n");

  scanf("%d",&find);

  int result = binarySearch(array,find, 0, size - 1);

  if (result == -1)

    printf("Not found");

  else

    printf("Element is found at index %d", result);

}

int binarySearch(int array[], int find, int low, int high)                         

{                                                                                                          

  if (high >= low) {

    int mid = low + (high - low) / 2;

 

    if (array[mid] == find)

      return mid;

    if (array[mid] > find)

      return binarySearch(array, find, low, mid - 1);

    return binarySearch(array,find, mid + 1, high);

  }

  return -1;

}

OUTPUT:






 

Comments

Popular posts from this blog

[ C++ program] Assume that a bank maintains two kinds of accounts for customers, | | one called as savings account and the other as current account. | | The savings account provides compound interest and withdrawal facilities but no cheque book facility. | | The current account provides cheque book facility but no interest. | | Current account holders should also maintain a minimum balance | | and if the balance falls below this level, a service charge is imposed. | | Create a class account that stores customer name, account number and type of account. | | From this derive the classes curacct and savacct to make them more specific to their requirements.

Perform all operation in a singly linked list using C language:

Write a program in C++ to create a base class shape and derive two classes named Circle and Square from it. Create and initialize objects from these classes using appropriate constructors.