C++ Programming (Binary Search) Using part of the code from question 1 provided
ID: 3694990 • Letter: C
Question
C++ Programming (Binary Search)
Using part of the code from question 1 provided below , you can start from step 3 in this question.
Here is the relevant portions of previous code to get the sorted array.
#include <iostream>
#include <fstream>
using namespace std;
void printArray(int arr[], int n);
void selectsort_ascending(int arr[], int n);
int main()
{
// declaring an array
int randomnums[20];
int size = 0;
int num;
// opening and reading from file
ifstream inputFile;
inputFile.open("numbers.txt");
while(size < 20 && inputFile >> num)
{
randomnums[size] = num;
size++;
}
// printing
printArray(randomnums, size);
inputFile.close();
//calling selection sort
selectsort_ascending(randomnums, size);
// printing
printArray(randomnums, size);
return 0;
}
void printArray(int arr[], int n)
{
for(int i=0; i<n; i++)
cout << arr[i ]<< " ";
cout << endl;
}
void selectsort_ascending(int arr[], int n)
{
//pos_min is short for position of min
int pos_min,
temp;
for (int i = 0; i < n - 1; i++)
{
pos_min = i;//set pos_min to the current index of array
for (int j = i + 1; j < n; j++)
{
if (arr[j] < arr[pos_min])
pos_min=j;
//pos_min will keep track of the index that min is in, this is needed when a swap happens
}
//if pos_min no longer equals i than a smaller value must have been found, so a swap must occur
if (pos_min != i)
{
temp = arr[i];
arr[i] = arr[pos_min];
arr[pos_min] = temp;
}
}
}
Explanation / Answer
Answer for Queston:
This below C++ Binary Search function will search the given element is present or not..
bool bsearch(int AR[], int N, int VAL)
{
int Mid,Lbound=0,Ubound=N-1;
while(Lbound<=Ubound)
{
Mid=(Lbound+Ubound)/2;
if(VAL>AR[Mid])
Lbound=Mid+1;
else if(VAL<AR[Mid])
Ubound=Mid-1;
else
return true;
}
return false;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.