IMPORTANT : C++ PROGRAM Write a function that takes an array Arr of size N and r
ID: 3573325 • Letter: I
Question
IMPORTANT : C++ PROGRAM
Write a function that takes an array Arr of size N and returns another array which, first disregards the numbers greater than a certain threshold (also a passed parameter), and then stores the remaining elements of the array Arr first in an increasing order and then in a decreasing order
Example: If Arr = {5,4,1,12,0,2} and threshold = 10, the returned array should be = {0,1,2,4,5,5,4,2,1,0}
In the main method, the user is asked to enter the size of array Arr, the value of the threshold, as well as all the elements of array Arr.
Notes and hints:
Write an iterative merge sort method to do the sorting part.
You may need to define additional functions.
The size of the returned array is dynamic (depending on the number of eliminated elements). Be careful how you return such an array.
Explanation / Answer
#include <iostream>
using namespace std;
int count=0;
void function_merge(int *,int,int,int);
void function_sort(int temp[], int left, int right)
{
if (left < right)
{
int middle = left+(right-left)/2;
function_sort(temp, left, middle);
function_sort(temp, middle+1, right);
function_merge(temp, left, middle, right);
}
}
void function_merge(int temp[], int left, int middle, int right)
{
int a, b, c;
int n1 = middle - left + 1;
int n2 = right - middle;
/* create temp arrays */
int lef[n1], ri[n2];
/* Copy data to temp arrays L[] and R[] */
for (a = 0; a < n1; a++)
lef[a] = temp[left + a];
for (b = 0; b < n2; b++)
ri[b] = temp[middle +b+1];
/* Merge the temp arrays back into arr[l..r]*/
a = 0;
b = 0;
c = left;
while (a < n1 && b < n2)
{
if (lef[a] <= ri[b])
{
temp[c] = lef[a];
a++;
}
else
{
temp[c] = ri[b];
b++;
}
c++;
}
/* copy leftover elements */
while (a < n1)
{
temp[c] = lef[a];
a++;
c++;
}
/* copy leftover elements from right array */
while (b < n2)
{
temp[c] = ri[b];
b++;
c++;
}
}
int * function(int *p,int n,int threshold)
{
int *arr2;
for(int i=0;i<n;i++)
{
if(p[i]>threshold)
count++;
}
arr2=new int[count*2];
int j=0;
for(int i=0;i<n;i++)
{
if(p[i]<threshold)
{
arr2[j]=p[i];
j++;
}
}
function_sort(arr2,0,count-1);
for(int i=count,j=count-1;j>=0;i++,j--)
{
arr2[i]=arr2[j];
}
return arr2;
}
// function to print array
void display(int *temp,int size)
{
int i;
cout<<" array elements are ";
for(i=0;i<size;i++)
cout<<temp[i];
}
int main(int argc, char** argv) {
int size,i,threshold,*arr,*res;
cout<<" enter array size";
cin>>size;
cout<<" enter threshold value";
cin>>threshold;
arr=new int[size];
cout<<" enter array elements";
for(i=0;i<size;i++)
cin>>arr[i];
res=function(arr,size,threshold);
display(res,count*2);
return 0;
}