Please use c++ programming, do it from scratch and also please comment or explai
ID: 3824517 • Letter: P
Question
Please use c++ programming, do it from scratch and also please comment or explain your codes. USe BinarySearch.h, BinarySearch.cpp, BinarySearch_test.cpp .
Thanks.
BinarySearch
Requested files: BinarySearch.h, BinarySearch.cpp, BinarySearch_test.cpp (Download)
Type of work: Individual work
Write a program that will use a recursive binary search to locate an integer in a sorted array. The integer values will be provided in a file named datarray.bin. You should dynamically allocate memory sufficient to hold all elements in this array and read the contents of this file into your data structure.
Your code must implement a function called recursiveBinarySearch(int start_index, int end_index, int_targetValue) which will perform the binary search.
You should test you class with a driver program named BinarySearch_test.cpp
Explanation / Answer
#include<iostream>
#include <fstream>
#include "BinarySearch.h"
using namespace std;
int * readFromFile()
{
int *array;
int tmp, count;
ifstream fin("/home/zubair/Desktop/data.txt");
while(fin >> tmp)
count++;
array = new int[count];
fin.close();
fin.open("/home/zubair/Desktop/data.txt");
int i=0;
while(fin >> tmp)
array[i++]=tmp;
return array;
}
int main()
{
int *arr = readFromFile();
BinarySearch binary;
int index = binary.recursiveBinarySearch(arr, 0, 8, 6);
if (index == -1)
cout << "Element not found" << endl;
else
cout << "Element found at location "<< index;
}
-------------------------------------------------------------------------------------------------------------
#ifndef BINARYSEARCH
#define BINARYSEARCH
using namespace std;
class BinarySearch
{
public:
int recursiveBinarySearch(int *arr, int start_index, int end_index, int target_val);
};
#endif
-------------------------------------------------------------------------------------------------------------
#include<iostream>
#include <fstream>
#include "BinarySearch.h"
using namespace std;
int * readFromFile()
{
int *array;
int tmp, count;
ifstream fin("/home/zubair/Desktop/data.txt");
while(fin >> tmp)
count++;
array = new int[count];
fin.close();
fin.open("/home/zubair/Desktop/data.txt");
int i=0;
while(fin >> tmp)
array[i++]=tmp;
return array;
}
int main()
{
int *arr = readFromFile();
BinarySearch binary;
int index = binary.recursiveBinarySearch(arr, 0, 8, 6);
if (index == -1)
cout << "Element not found" << endl;
else
cout << "Element found at location "<< index;
}