The instructions for my lab are posted below. The program must build in Microsof
ID: 3556494 • Letter: T
Question
The instructions for my lab are posted below. The program must build in Microsoft Visual C++. Please use headers so the program will compile. Thank you
Create an array of 10 integers then
1) using a function prompt the user for input values for the array
2) using a function sort the array using one of the sorting methods described in the book
3) using a function prompt the user for an integer value and using a binary search determine if the value is in the array or not and if the integer is in the array print out its index value.
Be sure to insert spaces in the output for readability.
Explanation / Answer
#include <iostream>
using namespace std;
void insertionSort(int arr[],int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i-1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}
int BinarySearch(int A[], int l, int r, int key)
{
int m;
while( l <= r )
{
m = l + (r-l)/2;
if( A[m] == key ) // first comparison
return m;
if( A[m] < key ) // second comparison
l = m + 1;
else
r = m - 1;
}
return -1;
}
int main() {
int Array[10];
cout<<"Enter array elements";
for(int i=0;i<10;i++)
{
cin>>Array[i];
}
insertionSort(Array,10);
int srch_element;
cout<<"Enter the element to be searched";
cin>>srch_element;
int result=BinarySearch(Array, 0, 9, srch_element);
if(result!=-1)
cout<<"Element found at "<<result+1<<"th position";
else
cout<<"element Not found";
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.