Binary Search coderinme

Binary Search coderinme

Binary Search coderinme
First of all, what a binary search does? In this process, we search a particular item by comparing the middle most item of the array. If a get a match, then the index of item is returned. But if the middle item is greater than the item, then item is search in sub-array to the right of the middle item other wise the item is search in the sub-array to the left of the middle item. This process continues on the sub-array as well until the size of sub-array reduces to zero.

Now let us Write a program to search an element in a given array use binary search algorithm.

#include<stdio.h>
int main()
{
int a[20],i,n,m,c=0,l,u,mid;
printf("\nEnter the size of an array: ");
scanf("%d",&n);
printf("\nEnter the elements in ascending order: \n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nEnter the number to be searched: ");
scanf("%d",&m);
l=0;
u=n-1;
while(l <= u){
mid = ( l + u ) / 2;
if(m == a[mid])
{
c = 1;
break;
}
else if( m < a[mid]){
u = mid - 1;
}
else
l = mid + 1;
}
if(c == 0)
printf("\nThe number is not found.");
else
printf("\nThe number is found.");
getch();
return 0;
}

For more programs in C, visit our C Coder Archives

Binary Search coderinme

All rights reserved. No part of this Post may be copied, distributed, or transmitted in any form or by any means, without the prior written permission of the website admin, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. For permission requests, write to the owner, addressed “Attention: Permissions Coordinator,” to the admin @coderinme

Leave a reply:

Your email address will not be published.