0% found this document useful (0 votes)
13 views

Binary

The document describes a binary search algorithm implemented in C code. The code takes an array as input, searches for a target element using a binary search approach, and returns the index if found or -1 if not found. It prompts the user to enter the array size and elements, the target element to search for, performs the binary search using a recursive function, and prints the result.

Uploaded by

Chirag Bhatia
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Binary

The document describes a binary search algorithm implemented in C code. The code takes an array as input, searches for a target element using a binary search approach, and returns the index if found or -1 if not found. It prompts the user to enter the array size and elements, the target element to search for, performs the binary search using a recursive function, and prints the result.

Uploaded by

Chirag Bhatia
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 1

Binary search

#include<stdio.h> #include<conio.h> int bsearch(int[],int,int); void main() {int AR[50],ITEM,N,index; printf("enter desired array size(max 50)..."); scanf("%d",&N); printf("\nEnter array elements\n"); for(int i=0;i<N;i++) {scanf("%d",&AR[i];} printf("element to be searched for....."); scanf("%d",&ITEM); index=Bsearch(AR,N,ITEM); if (index==-1) printf("\nsorry!!given element could'nt be found\n"); else printf("\nElement found at index:%d,position:%d "index,index+1); getch(); } int Bsearch(int AR[],int size,int ITEM) {int beg,last,mid; beg=0;last=size-1; while(beg<=last) {mid=(beg+last)/2; if (ITEM==AR[mid]) return mid; else if(ITEM>AR[mid]) beg=mid+1; else last=mid-1; } return -1; }

Output
enter desired array size(max 50)...5 Enter array elements 4 6 8 9 12 element to be searched for.....6 Element found at index:1,position:2

You might also like