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

Program For Binary Search

This program implements a binary search algorithm to search for a target element in a sorted array. The program takes user input for the array size and elements, the target item, performs a recursive binary search, and outputs whether the item was found and the search cost. It recursively halves the search space at each step by comparing the target to the middle element until the target is found or the search space is empty.

Uploaded by

meghanshsharma
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)
31 views

Program For Binary Search

This program implements a binary search algorithm to search for a target element in a sorted array. The program takes user input for the array size and elements, the target item, performs a recursive binary search, and outputs whether the item was found and the search cost. It recursively halves the search space at each step by comparing the target to the middle element until the target is found or the search space is empty.

Uploaded by

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

PROGRAM FOR BINARY SEARCH

#include<stdio.h> //Header file #include<conio.h> //Header file for clrscr() int bin_search(int b[50], int low, int high); int item, cost=0; void main() { int a[50],i,n,loc; //Declaration clrscr(); //Function to clear screen printf(" \n \t \t BINARY SEARCH\n \n "); printf(" Enter the size of array:" ); scanf( "%d" , &n ); printf(" \n Enter Array Elements(ascending order) :\n" ); for( i=0 ; i<n ; i++ ) scanf( "%d" , &a[i] ); printf( "\n Enter the element to be searched: " ); scanf( "%d" , &item ); printf( "\n Result of binary search:\n " ); loc = bin_search(a , 0 , n); if(loc = = 0) printf( "Unsuccessful search. %d not found.\n" , item); else { printf( " Successful search\n" ); printf( "%d found at position %d. \n" , item , loc); } printf( "The cost of running binary search is %d. \n" , cost ); getch( ); //Holds the output screen } int bin_search( int b[50] , int low , int high) { int mid , i; if(low < = high) { cost ++ ; mid = (low+high) / 2; if( item < b[mid] ) { high = mid - 1; bin_search( b , low , high); } else if( item > b[mid] ) { low = mid + 1;

bin_search( b , low , high ); } else return(mid + 1); } else return(0); } OUTPUT: BINARY SEARCH Enter the size of array:5 Enter Array Elements(ascending order) : 1 4 7 12 20 Enter the element to be searched: 12 Result of binary search: Successful search 12 found at position 4. The cost of running binary search is 3.

You might also like