Write a Program to find element in a array using Binary Search.

Working

Binary Search is Working with the Sorted Array. if the array is not sorted then using Sorting Algorithm make an Array to Sort. In Binary Search Compare start from the middle of array if Searching Element is lower is middle goes to left side one by one, if the Searching Element is Greater then the middle Element its goes right side one by one.

  • Make An Array
  • If Un-Sorted Array
    • Make the Sorted Array
  • Left = 0
  • right = array_length – 1
  • Loop Start
    • middle = (left+right)/2
    • if search_number is equal with middle Element
      • return middle Index
      • break; // Search Number is Found
    • if search_number greater than  middle Element
      • left = middle + 1
    • else
      • right = middle – 1
  • End Loop

 

Program 

//Binary Search
#include<iostream.h>
#include<conio.h>
void display_array(int array[],int length){
for(int i=0;i<length;i++){
cout<<array[i];
(i==length-1)? cout<<".":cout<<",";
}
}
int binary_search(int array[],int length,int search_number){
int left=0; // Left of Array Segment
int right=length-1; // Right of Array Segment
while(left<=right){
int middle = (left+right)/2; // Middle of Array Segment
if(search_number==array[middle]){
return middle;
break; // Search Number is Found
}
if(search_number > array[middle]){
left = middle + 1;
}else{
right = middle - 1;
}
}
return -1;// Search Number Not Found
}
void sorting(int array[],int length){

for(int i = length - 1; i >= 0; i--){
for(int j = 1; j <= i; j++){
if(array[j-1] > array[j]){
//Swap
int temp_A = array[j-1];
array[j-1] = array[j];
array[j] = temp_A;
}
}
}
}
void main(){
clrscr();
int array[10]={12,34,21,39,65,48,36,11,58,23};
int number,found;
cout<<"\n Binary Search";
cout<<"\n -------------";
cout<<"\n Un-Sorted Elements in a Array ";
display_array(array,10);
//Sorting
cout<<"\n\n Binary Search is Works With Sorted Array.. ";
sorting(array,10);
cout<<"\n\n After Sorting Sorted Elements in a Array ";
display_array(array,10);
cout<<"\n Enter Number to be Search : ";
cin>>number;
found = binary_search(array,10,number);
if(found>-1){
cout<<"\n Number Found at index of "<<found;
}else{
cout<<"\n "<<number<<" is not Found in Array ";
}
getch();
}

Output 

Element is Found


Element is Not Found

(Visited 81 times, 1 visits today)
Share with Friends :

Leave a Reply

Your email address will not be published. Required fields are marked *