codescracker
c

C Program for Binary Search



« Previous Program Next Program »

In this article, you'll learn and get code about how to search an element from given array using binary search technique. But before going through the program, if you are not aware of how binary search works, then I recommend you to go through the step by step working of Binary search.

Here are the list of programs you will go through over here, with its step by step explanation:

Binary Search in C

This is the simplest program of binary search. Simplest in the sense, here we have directly asked from user to enter 10 element or numbers without giving to specify the size of array and then enter his/her required amount of element. Also the sorting code block is not included in this program. So I've just asked to enter already sorted array as input. Let's take a look at the program:

// Binary Search in C
// ----codescracker.com------

#include<stdio.h>
#include<conio.h>
int main()
{
    int i, arr[10], search, first, last, middle;
    printf("Enter 10 elements (in ascending order): ");
    for(i=0; i<10; i++)
        scanf("%d", &arr[i]);
    printf("\nEnter element to be search: ");
    scanf("%d", &search);
    first = 0;
    last = 9;
    middle = (first+last)/2;
    while(first <= last)
    {
        if(arr[middle]<search)
            first = middle+1;
        else if(arr[middle]==search)
        {
            printf("\nThe number, %d found at Position %d", search, middle+1);
            break;
        }
        else
            last = middle-1;
        middle = (first+last)/2;
    }
    if(first>last)
        printf("\nThe number, %d is not found in given Array", search);
    getch();
    return 0;
}

This program was written under Code::Blocks IDE. Here is the initial snapshot of sample run:

binary search c

Now provide any 10 elements in ascending order, say 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10 and then press ENTER key. Again enter any element or number to be search say 7, press ENTER key to see the output given in the snapshot here:

c binary search program

If user supply all the 10 numbers as entered in above output. But this time, when he/she entered any number say 15 to be search from the given list of number, then here is the output you will see:

binary search in c

Program Explained

  1. Declare all the required variable say i, arr[], search, first, last, middle of int (integer type)
  2. Here arr[] is declared of size 10 to store upto 10 elements or numbers
  3. Now receive 10 numbers as input from user
  4. As indexing in an array starts from 0, so first element gets stored in arr[0], second element gets stored in arr[1], and so on
  5. Now ask to enter the number to be search and store it in search variable
  6. Now initialize 0 to first (index), 9 to last (index), and find the value of middle (index) using first+last/2
  7. Create a while loop, that continue running until the value of first (index) becomes less than or equal to the value of last (index)
  8. The meaning of above step is, process inside the loop continue running until the interval becomes zero, as told in the logic given at start of this article
  9. Inside the while loop, first check whether value at middle index (arr[middle]) is less than search (number to be search) or not using if statement
  10. If it is, then initialize middle+1 to first and go to the last statement of the loop, that is middle = (first+last)/2
  11. If 9th step evaluates to be false, then follow further step given below
  12. Now program flow goes to else-if part and checks whether element at middle (arr[middle]) is equal to search (number to be search) or not
  13. If it is equal, then print the position. Here we have added the index number by one to display the position of the number. As indexing starts from 0. For example, in an array, there are 4 numbers say 10, 20, 30, 40. So, the index will be 0, 1, 2, 3. But normally people knows like this:
    • 10 preset at first position
    • 20 present at second position
    • 30 present at third position
    • 40 present at fourth position
  14. So i have added 1 to middle and prints its value as the position of the given number in array
  15. Now the program flow goes to the last statement of the while loop, that is middle = (first+last)/2;
  16. If 12th step evaluates to be false, then else block gets evaluated, and middle-1 is assigned to last and continue running the loop until the condition of while loop evaluates to be false

Here is the modified version of binary search program (as given above) in C. Here we have leave the size of array to be decided by user at run-time. And before performing the binary search, bubble sort is used to sort the given array in ascending order.

Important - This program finds the position of number from sorted array, not from the actual array that is entered by user at run-time. For example, if user supply 10, 50, 20, 30, 40 as array input, and 20 as number to be search. Then this program sort the array, so the array becomes 10, 20, 30, 40, 50 and the position of 20 will be 2.

// Complete Version of Biinary Search Program in C
// ----codescracker.com------

#include<stdio.h>
#include<conio.h>
int main()
{
    int i, j, n, arr[100], search, first, last, middle, temp;
    printf("How many element you want to store in array ? ");
    scanf("%d", &n);
    printf("\nEnter %d array elements: ", n);
    for(i=0; i<n; i++)
        scanf("%d", &arr[i]);
    printf("\nEnter element to be search: ");
    scanf("%d", &search);
    // sorting given array using bubble sort
    for(i=0; i<(n-1); i++)
    {
        for(j=0; j<(n-i-1); j++)
        {
            if(arr[j]>arr[j+1])
            {
                temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
    // sort array
    printf("\nNow the sorted Array is:\n");
    for(i=0; i<n; i++)
        printf("%d ", arr[i]);
    // back to binary search
    first = 0;
    last = n-1;
    middle = (first+last)/2;
    while(first <= last)
    {
        if(arr[middle]<search)
            first = middle+1;
        else if(arr[middle]==search)
        {
            printf("\n\nThe number, %d found at Position %d", search, middle+1);
            break;
        }
        else
            last = middle-1;
        middle = (first+last)/2;
    }
    if(first>last)
        printf("\nThe number, %d is not found in given Array", search);
    getch();
    return 0;
}

Here is the snapshot of sample run:

c binary search example

using User-defined Function

Now modify the first program of this article that does the same job but this time using function as shown in the program given below:

// Binary Search Program in C using Function
// ----codescracker.com------

#include<stdio.h>
#include<conio.h>
int binarySearchFun(int arr[], int);
int main()
{
    int i, arr[10], search, pos;
    printf("Enter 10 elements (in ascending order): ");
    for(i=0; i<10; i++)
        scanf("%d", &arr[i]);
    printf("\nEnter element to be search: ");
    scanf("%d", &search);
    pos = binarySearchFun(arr, search);
    if(pos==0)
        printf("\nThe number, %d is not found in given Array", search);
    else
        printf("\nThe number, %d found at Position %d", search, pos);
    getch();
    return 0;
}
int binarySearchFun(int arr[], int search)
{
    int first, last, middle;
    first = 0;
    last = 9;
    middle = (first+last)/2;
    while(first <= last)
    {
        if(arr[middle]<search)
            first = middle+1;
        else if(arr[middle]==search)
        {
            return (middle+1);
        }
        else
            last = middle-1;
        middle = (first+last)/2;
    }
    return 0;
}

This is the snapshot of sample output produced after running the above program:

binary search in c using function

Program Explained

To learn more about function, refer to Function in C tutorial.

using Recursion

This is the last program on binary search. This program used recursive function to find the number from the given array using binary search technique. Let's take a look at the program:

// Binary Search Program in C using Recursion
// ----codescracker.com------

#include<stdio.h>
#include<conio.h>
int binarySearchRecFun(int [], int, int, int);
int main()
{
    int i, arr[10], search, pos;
    printf("Enter 10 elements (in ascending order): ");
    for(i=0; i<10; i++)
        scanf("%d", &arr[i]);
    printf("\nEnter element to be search: ");
    scanf("%d", &search);
    pos = binarySearchRecFun(arr, 0, 9, search);
    if(pos==0)
        printf("\nThe number, %d is not found in given Array", search);
    else
        printf("\nThe number, %d found at Position %d", search, pos);
    getch();
    return 0;
}
int binarySearchRecFun(int arr[], int first, int last, int search)
{
    int middle;
    if(first>last)
        return 0;
    middle = (first+last)/2;
    if(arr[middle]==search)
        return (middle+1);
    else if(arr[middle]>search)
        binarySearchRecFun(arr, first, middle-1, search);
    else if(arr[middle]<search)
        binarySearchRecFun(arr, middle+1, last, search);
}

You will get the same output as shown in the output of above program, that is, binary search using function. To learn more about recursion, refer to Recursion in C tutorial.

Same Program in Other Languages

C Online Test


« Previous Program Next Program »



© Copyright 2021. All Rights Reserved.

CodesCracker