Selection Sort and Binary Search 20 points Populate an array
Selection Sort and Binary Search (20 points)
Populate an array randomNums of size 50 with random integers in the range 0-500. Further, a) Print the elements of the array randomNums after initialization. b) Perform selection sort on randomNums, and sort the array in increasing order. c) Print the elements of randomNums after sorting. d) Create another array terminalSum of size 25. e) Initialize each element of terminalSum by adding each pair of terminal elements from randomNums. Print terminalSum array after initialization. For Example: terminalSum 1 st element = randomNums 1 st element + randomNums 50th element. terminalSum 2 nd element = randomNums 2 nd element + randomNums 49th element. . terminalSum 25th element = randomNums 25th element + randomNums 26th element. f) Perform selection sort on terminalSum, and sort the array in decreasing order g) Ask the user for a number (0-500) and binary search it in the sorted terminalSum. Report the index location if found else report not found. h) Print the elements of the array terminalSum after sorting.
THIS IS WHAT I HAVE SO FAR, I DON\'T CARE IF YOU USE IT OR WRITE SOMETHING COMPLETELY NEW AS LONG AS IT WORKS CORRECTLY, THANK YOU:
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int main()
{
//Initialize random seed
srand(time(NULL));
int array[50];
for(int i=0; i < 50; i++)
{
//generate random numbers
int x = rand()% 500+1;
array[i] = x;
}
//for(int i = 0; i < 50; i++)
//{
//cout << array[i]<<endl;
//}
for(int count = 0; count < 50; count++)
{
int max = 0;
for(int count2 = 0; count2 < 50 - count; count2++ )
{
if(array[max] < array[count2])
{
max = count2;
}
}
int temp = array[50-count-1];
array[50-count-1] = array[max];
array[max] = temp;
}
for(int i = 0; i < 50; i++)
{
cout << array[i]<<endl;
}
}
Solution
#include<iostream.h>
#include<conio.h>
void main()
{
int n, i, ahgh[50], srch, frst, lst, mddle;
cout<<\"Enter total number of elements :\";
cin>>n;
cout<<\"Enter \"<<n<<\" number :\";
for (i=0; i<n; i++)
{
cin>>ahgh[i];
}
cout<<\"Enter a number to find :\";
cin>>srch;
frst = 0;
lst = n-1;
mddle = (frst+lst)/2;
while (frst <= lst)
{
if(ahgh[mddle] < srch)
{
frst = mddle + 1;
}
else if(ahgh[mddle] == srch)
{
cout<<srch<<\" found at location \"<<mddle+1<<\"\ \";
break;
}
else
{
lst = mddle - 1;
}
mddle = (frst + lst)/2;
}
if(frst > lst)
{
cout<<\"Not found! \"<<srch<<\" is not present in the list.\";
}
getch();
}

