Modify the sequential search and binary search program below so that they use po
ID: 3605077 • Letter: M
Question
Modify the sequential search and binary search program below so that they use pointer notation to access array elements. Do not use [ ] to retrieve an element of the array. Use * and / or & instead.
#include<iostream>
#include<fstream>
using namespace std;
void binsearch(int arr[], int x)
{
int l = 0;
int r = 9;
int count = 0;
while (l <= r)
{
int m = l + (r-l)/2;
if (arr[m] == x)
count++;
if (arr[m] < x)
l = m + 1;
else
r = m - 1;
}
cout << x << " appeared " << x << " times ";
}
int main(){
ifstream fin("unsortedNumbers.txt");
ofstream fout("sortedNumbers.txt");
int data[10];
int temp;
int n;
if (!fin) {
cout << "Error in opening file ";
return 0;
}
for (int i = 0; i<10; i++){
fin >> data[i];
}
fin.close();
for (int i = 0; i<10; i++){
for(int j=i+1; j<10; j++){
if (data[i] > data[j]){
temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
}
for (int i = 0; i<10; i++){
fout << data[i] << " ";
}
fout << endl;
fout.close();
cout << "Minimum :" << data[0] << endl;
cout << "Maximum :" << data[9] << endl;
cout << "Enter the number to search : " ;
cin >> n;
binsearch(data,n);
return 0;
}
Explanation / Answer
To convert from index based accessing to pointer based:
arr[m] becomes *(arr+m)
The rest of the code will remain the same.
arr is the starting position of the array. (arr+m) is arr[0+m] i.e arr[m]
I hope its clear. :)
*****************************************************************************************************
#include<iostream>
#include<fstream>
using namespace std;
void binsearch(int arr[], int x)
{
int l = 0;
int r = 9;
int count = 0;
while (l <= r)
{
int m = l + (r-l)/2;
if (*(arr+m) == x)
count++;
if (*(arr+m) < x)
l = m + 1;
else
r = m - 1;
}
cout << x << " appeared " << x << " times ";
}
int main(){
ifstream fin("unsortedNumbers.txt");
ofstream fout("sortedNumbers.txt");
int data[10];
int temp;
int n;
if (!fin) {
cout << "Error in opening file ";
return 0;
}
for (int i = 0; i<10; i++){
fin >> *(data+i);
}
fin.close();
for (int i = 0; i<10; i++){
for(int j=i+1; j<10; j++){
if ( *(data+i) > *(data+j) ){
temp = *(data+i);
*(data+i) = *(data+j);
*(data+j) = temp;
}
}
}
for (int i = 0; i<10; i++){
fout << *(data+i) << " ";
}
fout << endl;
fout.close();
cout << "Minimum :" << *(data+0) << endl;
cout << "Maximum :" << *(data+9) << endl;
cout << "Enter the number to search : " ;
cin >> n;
binsearch(data,n);
return 0;
}
*************************************************************************************************************
Output screens:
I hope this helps you.
If you find my answer helpful,
Kindly rate the answer.
All the best :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.