First, generate an array of 20 input random integers in the range between 0 to 3
ID: 3660952 • Letter: F
Question
First, generate an array of 20 input random integers in the range between 0 to 30 and display. Then, sort the generated 20 random integer numbers in ascending order using "THE SELECTION SORT" method and display your sorted output data flow chart. Next, generate a single random integer number in the same range between 0 to 30, display and then search this generated single random integer value in your sorted array using " THE BINARY SEARCH" method and display your result. If the number is found, display the value with its array subscript. Otherwise, display a message that "the value was not in the array"Explanation / Answer
#include<iostream>
#include<cstdlib>
using namespace std;
int random_number_in_range(int min, int max)
{
return min + (rand() % (int)(max - min + 1));
}
void selection_sort (int *a, int n)
{
int i, j, m, t;
for (i = 0; i < n; i++)
{
for (j = i, m = i; j < n; j++)
{
if (a[j] < a[m])
m = j;
}
t = a[i];
a[i] = a[m];
a[m] = t;
}
}
template <class T>
int binary_search(const T array[], int len, T what)
{
if (len == 0) return -1;
int mid = len / 2;
if (array[mid] == what) return mid;
if (array[mid] < what) {
int result = binary_search(array+mid+1, len-(mid+1), what);
if (result == -1) return -1;
else return result + mid+1;
}
if (array[mid] > what)
return binary_search(array, mid, what);
}
int main(int argc, char *argv[])
{
srand(time(NULL));
int numbers[20];
for (int i = 0; i < 20; ++i)
{
numbers[i] = random_number_in_range(0,30);
cout << numbers[i] << " ";
}
cout << endl;
selection_sort(numbers, 20);
for (int i = 0; i < 20; ++i)
{
cout << numbers[i] << " ";
}
cout << endl;
int random = random_number_in_range(0,30);
int index = binary_search(numbers, 20, random);
cout << "Binary search for " << random << "." << endl;
if (index == -1)
{
cout << "The value was not in the array." << endl;
}
else
{
cout << "Found " << random << " at index " << index << "." << endl;
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.