#1
31st January 2016, 12:54 PM
|
|||
|
|||
How to solve below given C++ program question?
Wite a program in c++ to read an array of stored integers. Search for a value using binary search method. If the element is found, part its location else print element not found.
Please help me with this question. |
#2
31st January 2016, 09:56 PM
|
|||
|
|||
Re: How to solve below given C++ program question?
This is the program for storing 5 integers using arrays in C++
#include <iostream> using namespace std; int main() { int n[5]; cout<<"Enter 5 numbers: "; /* Storing 5 number entered by user in an array using for loop. */ for (int i = 0; i < 5; ++i) { cin>>n[i]; } cout<<"First number: "<<n[0]<<endl; // first element of an array is n[0] cout<<"Last number: "<<n[4]; // last element of an array is n[SIZE_OF_ARRAY - 1] return 0; } Program for Binary Search Algorithm Binary Search is the process of searching by dividing the set of integers in to two parts and then searching for the algorithm # include <iostream.h> # include <conio.h> int binary_search(int [],int,int); main( ) { clrscr( ); constint array_size=10; int array[array_size]={0,6,9,12,20,23,29,32,47,79}; cout<<" ******"<<endl; cout<<" ****"<<endl; cout<<" ********"<<endl; gotoxy(1,24); cout<<" *******"<<endl; cout<<" *****"; gotoxy(1,5); cout<<"\n The contents of the array are : "<<endl; cout<<"\n Elements :"<<"\t\t Value:"<<endl; for(int count=0;count<array_size;count++) { cout<<"\t"<<" array ["<<count<<"]"<<"\t\t"; cout<<array[count]<<endl; } int searching_element=0; int flag=0; cout<<"\n Enter the element you want to find = "; cin>>searching_element; flag=binary_search(array,array_size,searching_elem ent); if(flag!=-1) cout<<"\n The given element is found at the position array["<<flag<<"]."; else cout<<"\n The given element is not found."; getch( ); return 0; } array[],int array_size,int element) { int start=0; int end=array_size-1; int middle; int position=-1; middle=(start+end)/2; do { if(element<array[middle]) end=middle-1; elseif(element>array[middle]) start=middle+1; middle=(start+end)/2; } while(start<=end && array[middle]!=element); if(array[middle]==element) position=middle; return position; } |
Related Topics: |
||
Thread | Replies | Last Post |
Right place in Kota or nearby for training program? Best program for Electrical student? | 1 | 28th March 2023 05:10 PM |
|