binary search using iteration in c
On-campus and online computer science courses to Learn the basic concepts of Computer Science.This tutorial will cover c ,c++, java, data structure and algorithm,computer graphics,microprocessor,analysis of algorithms,Digital Logic Design and Analysis,computer architecture,computer networks,operating system.
code in C:#include<stdio.h> int binary(int a[],int n,int search,int low,int high) { int mid,index=0; if(low<=high) { mid=(low+high)/2; if(search==a[mid]) index=mid; else if(search<a[mid]) return binary(a,n,search,low,mid-1); else return binary(a,n,search,mid+1,high); } else return index; } int main() { int a[10],i,n,search,index,low,high; printf("Enter the size of an array: "); scanf("%d",&n); printf("Enter the elements of the array: \n" ); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("Enter the number to be search: "); scanf("%d",&search); low=0,high=n-1; index=binary(a,n,search,low,high); if(index==0) printf("Number is not found."); else printf("Number %d is found at %d position",search,index+1); return 0; }output:-
Enter the size of an array: 5 Enter the elements of the array: 21 27 29 51 58 Enter the number to be search: 29 Number 29 is found at 3 position --------------------------------
0 comments: