Simple Binary search code example in cpp
Write a cpp program which takes some elements in an array and a Key in variable then program use Binary Search c++ Algorithm to find the key.
Concept used:
Functions, loop, and if-else statements in c++Program Explanation:
Program has two functions
Concept used:
Functions, loop, and if-else statements in c++Program Explanation:
Program has two functions
- One to sort array using bubble sort
- Second to apply Binary Search on array
- As it is necessary condition to sort the array before applying binary search in main after taking some elements as input in array.
- Array passes to bubble sort function to sort the array.
- After sorting array passes to Binary Search function which is of bool type if element found in array it true else false to main function.
C++ code for Binary Search
#include<iostream>
using namespace std;
// Prototypes of Functions
void bubbleSort(int array[], int size);
bool binarySearch(int array[], int size,int key);
int main(){
cout<<"Enter 5 numbers randomly : "<<endl;
// Size can be change by replacing 5
int array[5]; //Declaring array
for(int i=0; i<5; i++)
{
cout<<"t"; cin>>array[i]; // Initializing array
}
//Passing Arrary for Sorting
bubbleSort(array,5);
// Array has Sorted At This Point
cout<<"ntttEnter Key To Search: ";
int key;
cin>>key;
//Passing Array, size and key To Search Key
int result=binarySearch(array,5,key);
if(result==1)
cout<<"ntttKey Found in Array "<<endl;
else
cout<<"ntttKey NOT Found in Array "<<endl;
return 0;
}
void bubbleSort(int array[], int size){
cout<<" Input array is: "<<endl;
for(int j=0; j<size; j++)
{
//Displaying Array
cout<<"tttValue at "<<j<<" Index: "<<array[j]<<endl;
}
cout<<endl;
// Bubble Sort Starts Here
int temp;
for(int i2=0; i2<size; i2++)
{
for(int j=0; j<size-1; j++)
{
//Swapping element in if statement
if(array[j]>array[j+1])
{
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
// Displaying Sorted array
cout<<" Sorted Array is: "<<endl;
for(int i3=0; i3<size; i3++)
{
cout<<"tttValue at "<<i3<<" Index: "<<array[i3]<<endl;
}
}// Sort Function Ends Here
bool binarySearch(int array[],int size, int key){
int start=1, end=size;
int mid=(start+end)/2;
while(start<=end&&array[mid]!=key){
if(array[mid]<key){
start=mid+1;
}
else{
end=mid-1;
}
mid=(start+end)/2;
}// While Loop End
if(array[mid]==key)
return true; //Returnig to main
else
return false;//Returnig to main
cout<<"nnn";
}// binarySearch Function Ends Here
0 comments:
Post a Comment
Click to see the code!
To insert emoticon you must added at least one space before the code.