Need help on follwoing program using c language Write a recu

Need help on follwoing program using c++ language.

Write a recursive function that returns both the smallest and the largest element in an int array. Also, write a program to test your function.

Solution

Write a recursive function that returns both the smallest and the largest element in an int array.

Answer :-


#include <stdio.h>
#include <string>
#include <iostream>
#include <math.h>
#include <time.h>
using namespace std;

void recursMax(int* a, int size, int* maxValue)
{
   int half = size / 2;
   int* newMax = new int[half];
   for (int i = 0; i<half; i++)
   {
       newMax[i] = a[i]>a[size - i - 1] ? a[i] : a[size - i - 1];
   }
   if (half>1)
   {
       recursMax(newMax, half, maxValue);
   }
   if (half == 1)
   {
       *maxValue = newMax[0];
       delete[] newMax;
   }
}

void recursMin(int* a, int size, int* minValue)
{
   int half = size / 2;
   int* newMin = new int[half];
   for (int i = 0; i<half; i++)
   {
       newMin[i] = a[i]<a[size - i - 1] ? a[i] : a[size - i - 1];
   }

   if (half>1)
   {
       recursMin(newMin, half, minValue);
   }
   if (half == 1)
   {
       *minValue = newMin[0];
       delete[] newMin;
   }
}

int main()
{
   int size = 100;
   int* a = new int[size];
   //srand(time(NULL));
   for (int i = 0; i<size; i++)
   {
       //a[i] = rand() % 1000;
       a[i]=i%1000;
       cout << \"Index : \" << i + 1 << \", \" << a[i] << endl;
   }
   cout << endl << endl << \"Now we look to find the max!\" << endl;
   int maxValue = 0;
   int minValue = 0;
   recursMax(a, size, &maxValue);
   cout << maxValue << endl;
   recursMin(a, size, &minValue);
   cout << \"Now we look for the min value!\" << endl << minValue << endl;
   cout << \"Checking the accuracy! First for Max value!\" << endl;
   for (int i = 0; i<size; i++)
   {
       cout << \"Index : \" << i + 1 << \", \" << maxValue - a[i] << endl;
   }
   cout << \"Checking the accuracy! Now for min value!\" << endl;
   for (int i = 0; i<size; i++)
   {
       cout << \"Index : \" << i + 1 << \", \" << a[i] - minValue << endl;
   }
   delete[] a;
   return 0;
}

Need help on follwoing program using c++ language. Write a recursive function that returns both the smallest and the largest element in an int array. Also, writ
Need help on follwoing program using c++ language. Write a recursive function that returns both the smallest and the largest element in an int array. Also, writ

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site