Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write, compile, and run a C++ program that generates 200 random integers in betw

ID: 3572023 • Letter: W

Question

Write, compile, and run a C++ program that generates 200 random integers in between 1 to 200. Some of the randomly generated integers may be repeated as well. Next sort the randomly generated 200 integers using the Bubble sort algorithm. Store the sorted numbers in an output data file. Then prompt the user to enter an integer in between 1 to 200 (inclusive) out of the keyboard as a key element. Next find out the location of the key element in the sorted array using both the binary search and the sequential search algorithms. The result returned by binary search and the sequential search algorithm may vary for repeated elements inside the sorted array. This is acceptable. Please write out the results returned by the binary search and the sequential search algorithms to the output data file. Also, please implement your Bubble sort algorithm, Binary Search and Sequential Search algorithms as three separate functions that will be called from the function main().

Explanation / Answer


#include <cstdlib>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>


using namespace std;

void bubblesort(int arr[],int n){
for (int i = 0; i < n-1; i++){
for (int j = 0; j < n - i - 1; j++){
if (arr[j] > arr[j + 1]){
swap(arr[j],arr[j+1]);
}
}
}
}

int seqsearch(int arr[],int n,int key){
int location=0;
for(int i=0;i<n;i++){
if(arr[i]==key){
location = i+1;
}
}
return location;
}

int binsearch(int arr[],int n,int key){
int i = 0;
int f = n;
int location = 0;
int m;
while(i<=f){
m= (i+f)/2;
if(arr[m]==key){
location=m;
break;
}
if(key<arr[m]) f=m-1;
if(key>arr[m]) i=m+1;
}
  
return location;
}


int main(int argc, char** argv) {
fstream myfile;
myfile.open("example.txt");
int n=200;
int arr[n];
  
for(int i=0;i<n;i++){
arr[i]=rand() % n + 1 ;
}
  
  
bubblesort(arr,n);
myfile << "Sorted Elements: " ;
for(int p=0; p<n; p++){
myfile << arr[p] << " " ;
}

int key;
cout << "Enter the number you want to search by sequential search: " ;
cin >> key ;
int loc;
loc = seqsearch(arr,n,key);
if(loc == 0){
cout << key << " is not in the sorted numbers" << endl;
myfile << key << " is not in the sorted numbers" << " ";
}
else{
myfile << "The number " << key << " at location: " << loc << " ";
}

int key1;
cout << "Enter the number you want to search by binary search: " ;
cin >> key1 ;
int bloc;
bloc = binsearch(arr,n,key1);
if(loc == 0){
cout << key1 << " is not in the sorted numbers" << endl;
myfile << key1 << " is not in the sorted numbers" << " ";
}
else{
myfile << "The number " << key1 << " at location: " << (bloc+1) << " ";
}


myfile.close();
  
return 0;
}