Update the followin program instructions are given,c++ data structures and algor
ID: 3792573 • Letter: U
Question
Update the followin program instructions are given,c++ data structures and algorithms. Thanks!
#include <iostream>
#include<stdlib.h>
using namespace std;
int sort(int array[], int n);
int main()
{
int array[1000], beg, mid, end, i, n=1000, num;
int sorted_array[1000];
int j;
for (int i = 0; i < n; i++)
{
array[i] = (rand() % n) + 1;
}
//Print the random number generated
/*for(int i = 0; i< n;i++)
{
cout<<array[i]<<' ';
}*/
//Sorting of array element
sort(array,n);
//Iniatialize beg and end value
beg = 0;
end = n-1;
cout << " Enter a value to be searched in an array ";
cin >> num;
// Run loop, while beg is less than end
for(i=0;i<1000;i++)
{
//Calculate mid value
mid = (beg + end)/2;
//If value is found at mid index then print the position and exit from the program
if(array[mid] == num )
{
cout << " Item found at position "<< (mid +1 )<<endl;
exit(0);
}
else if(num < array[mid])
{
end = mid-1;
}
}
cout <<"Value does not found"<<endl;
}
//Function Deination
//Implementation of bubble sort
int sort(int array[], int n)
{
int temp;
int i;
for (int x = 1; x <= n ; x++)
{
for (int i = 0; i < n-x; i++)
{
if (array[i] > array[i+1])
{
temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}
}
}
Explanation / Answer
Hi
I have updated the code and highlighted the code changes below.
#include <iostream>
#include<stdlib.h>
using namespace std;
int binarySearch(int inputArr[], int key,int n) {
int start = 0;
int end = n - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (key == inputArr[mid]) {
return mid;
}
if (key < inputArr[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
void insertionSort(int a[],int n) {
for (int i = 1; i <n; i++) {
int keyElement = a[i];
int j = i-1;
while ( (j > -1) && ( a [j] > keyElement ) ) {
a [j+1] = a [j];
j--;
}
a[j+1] = keyElement;
}
}
int main()
{
int array[1000], beg, mid, end, i, n=1000, num;
int sorted_array[1000];
int j;
for (int i = 0; i < n; i++)
{
array[i] = (rand() % n) + 1;
}
insertionSort(array, n);
//Print the random number generated
/*for(int i = 0; i< n;i++)
{
cout<<array[i]<<' ';
}*/
cout << " Enter a value to be searched in an array ";
cin >> num;
int index = binarySearch(array, num, n);
if(index != -1)
{
cout << " Item found at position "<< index<<endl;
exit(0);
}
else{
cout <<"Value does not found"<<endl;
}
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
Enter a value to be searched in an array 776
Item found at position 769
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
Enter a value to be searched in an array 66
Value does not found
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.