Code 2
Code 2
ID: 210310571886
Page No:
Aim:
Aim: Write a program to implement Binary Search
Theory: In computer science, binary search, also known as half-interval search, logarithmic search, or binary
chop, is a search algorithm that finds the position of a target value within a sorted array. Binary search
compares the target value to the middle element of the array.
Algorithm:
1. Find the midpoint of the array; this will be the element at arr[size/2]. The midpoint divides the array into
two smaller arrays: the lower half of the array consisting of elements 0 to midpoint - 1, and the upper half
of the array consisting of elements midpoint to size - 1.
4. If the array consists of only one element return NULL, indicating that there is no match; otherwise
5. If the key is less than the value extracted from arr[midpoint] search the lower half of the array by
recursively calling search; otherwise
Source Code:
binarySearch.c
#include<stdio.h>
int start=0;
while(start<=len)
int mid=(start+len)/2;
if(ar[mid]==data)
return mid+1;
else if(ar[mid]>data)
len= mid-1;
else{
start= mid+1;
return -1;
int main()
int n;
scanf("%d",&n);
ID: 210310571886
Page No:
printf("Enter the element in sorted form: ");
int ar[n];
scanf("%d",&ar[i]);
int key;
scanf("%d",&key);
int loc;
if(loc!=-1)
else{
return 0;
Test Case - 1
User Output
Enter the total number of elements: 7
Enter the element in sorted form: 11 22 33 44 55 66 77
Enter the element which you want to search: 55
The number 55 is found in the list at the position 5
Test Case - 2
User Output
Enter the total number of elements: 5
Enter the element in sorted form: 56 98 118 245 3337
Enter the element which you want to search: 69
ITS Engineering College 2021-2025-CSE_3_B1