20_10

Write a C program to search a number in an array using Binary search algorithm.

 Source code:

/*A Binary search is an efficient algorithm for finding an item from an ordered list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until it is narrowed down the possible locations to just one. First an array of size 10 will be taken. We will fill it by reading 10 integers. Then the key integer to be searched will be given as input.  */


#include <stdio.h>

int main()

{

int i, n=10, first, last, middle, search, array[10];


   /* Fill Array */

    printf("Enter the array: ");

    for (i = 0; i < n; i++)

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


   /* Read the value of the integer to be searched */

printf("Enter the number which to be search:");

    scanf("%d", &search);

    first = 0;

    last = n - 1;

    middle = (first+last)/2;


    while (first <= last) {

        if (array[middle] < search)

        first = middle + 1;

        else if (array[middle] == search) {

        printf("%d found at position %d.", search, middle+1);

        break;

      }

      else

          last = middle - 1;


      middle = (first + last)/2;

    }

    if (first > last)

    printf("%d is not there in the list.", search);

return 0;

}

Output:



No comments:

Post a Comment

Write a program in C to convert a decimal number to binary using recursion.

 Source code: //Write a program in C to convert a decimal number to binary using recursion. #include<stdio.h> long convertB_to_D(int d...