find max and min of array c++ using recursion without changing function - c++

I need help trying to find the min and max values in an array recursively in c++. the functions were given and cannot be changed.
I tried it out for both but for some reason nothing happens and the code does not enter the loop and I want to know what I am doing wrong. Here is my main and the min and max functions.
int main()
{
int array[] = { 46, 22, 7, 58, 91, 55, 31, 84, 12, 78 };
if (findMax(array, 10) == 91)
{
cout << "findMax is correct!" << endl;
}
if (findMin(array, 10) == 7)
{
cout << "findMin is correct!" << endl;
}
int findMax(int array[], int size)
{
int i = (size - 1);
int max = 0;
if (array[0] < array[i]) {
max = array[i];
findMax(array, size - 1);
}
return max;
return 0;
}
int findMin(int array[], int size)
{
int i = 0;
int j = size - 1;
if (i == j)
{
return array[i];
i++;
}
int temp = findMin(array, size);
if (array[i] < temp)
{
return array[i];
}
else
{
return temp;
}
}
}

Well, you simply go backwards, return the min of each pair of elements and then next level make array size one smaller. Example:
int findMin(int array[], int n)
{
// if size = 0 means whole array has been traversed
if (n == 1){
return array[0];
}
return min(array[n-1], findMin(array, n-1));
}
And you can do the findMax using the same methodology.

Related

Sort array using recursion

I have been trying to sort an array using recursion, but I am getting no output, can somebody help me with this, like why there is no output?
void sortarray(int arr[], int index, int key, int len){
if (index == len-2){
}
else{
if (key==len-1){
key=0;
sortarray(arr, index++, key, len );
}
else {
if (arr[key] > arr[key+1]){
swap(arr[key], arr[key+1]);
}
sortarray(arr, index, key++, len );
}
}
}
int main(){
int arr[5] = {5,6,4,3,2};
sortarray(arr, 0,0,5);
for(int i=0; i<5; i++){
cout << arr[i] << " ";
}
}
I fixed the segfault and simplified the code to make it more clear what it does. Namely, walks the array once and swap the key with the next if it's larger. This is not a valid sort algorithm:
#include <iostream>
using namespace std;
void sortarray(int arr[], int key, int len) {
// base case
if (key + 1 == len) return;
// recursive case
if (arr[key] > arr[key + 1]){
swap(arr[key], arr[key + 1]);
}
sortarray(arr, key + 1, len );
}
int main() {
int arr[] = {5,6,4,3,2};
int len = sizeof(arr) / sizeof(*arr);
sortarray(arr, 0, len);
for(int i = 0; i < len; i++) {
cout << arr[i] << " ";
}
return 0;
}
and the result is:
5 4 3 2 6
I made some edits to your code and it works now (don't mind the printArr function, it's there just because cycles in main are ugly):
#include <iostream>
using namespace std;
void printArr(int arr[], int size)
{
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void sortarray(int arr[], int index, int key, int len)
{
if (index < len)
{
if (key == len - 1) {
key = 0;
sortarray(arr, ++index, key, len);
}
else {
if (arr[key] > arr[key + 1]) {
swap(arr[key], arr[key + 1]);
}
sortarray(arr, index, ++key, len);
}
}
}
int main()
{
int arr[5] = { 5,6,4,3,2 };
cout << "Before sort:" << endl;
printArr(arr, sizeof(arr)/sizeof(*arr));
sortarray(arr, 0, 0, 5);
cout << "After sort:" << endl;
printArr(arr, sizeof(arr) / sizeof(*arr));
return 0;
}
So the first problem was missing iostream and std namespace.
Key changes in the algorithm itself were:
change argument++ to ++argument
change the first condition to (index < len)
As to why your code didn't work properly: the index missed the stopping condition and went over the value of len (thus the screen o' fives).
So this answers your question, but this algorithm you wrote breaks once there are two same values next to each other. There is a good reason we use cycles for sorting and unless recursion is the point, I would recommend abandoning it for this task.
This code works perfectly-:
void sortArr(int arr[],int index, int key, int len){
// static int index = 0;
// static int key = 0;
if (index == len-1){
}
else{
if (key==len-1){
key=0;
sortArr(arr,index+1,key,len );
}
else {
if (arr[key] > arr[key+1]){
swap(arr[key], arr[key+1]);
}
sortArr(arr, index, key+1 ,len );
}
}
}
int main(){
int arr[5] = {5,6,4,3,2};
sortarray(arr, 0, 5);
for(int i=0; i<5; i++) {
cout << arr[i] << " ";
}
return 0;
}
The output of the code is:
2 3 4 5 6

Blank output screen when I run this searching algorithm

I have been practicing median search algorithm, and this is what I wrote-
#include <iostream>
#include <stdlib.h>
using namespace std;
int S1[10] = { 0 };
int S2[1] = { 0 };
int S3[10] = { 0 };
int mediansearch(int A[], int k, int size)
{
int ran = rand() % size;
int i = 0;
int a = 0;
int b = 0;
int c = 0;
for (i = 0; i < size; i++)
{
if (A[ran] > A[i])
{
S1[a] = A[i];
a++;
}
else if (A[ran] == A[i])
{
S2[b] = A[i];
b++;
}
else
{
S3[c] = A[i];
c++;
}
}
if (a <= k)
{
return mediansearch(S1, k, a);
}
else if (a + b <= k)
{
return A[ran];
}
else
{
return mediansearch(S3, k - a - b, c);
}
}
int main()
{
int arr[] = { 6, 5, 4, 8, 99, 74, 23 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = mediansearch(arr, 5, n);
cout << "5th smallest is:" << x << endl;
}
And I have been getting output as-
Process returned -1073741676 (0xC0000094) execution time : 1.704 s
So, what am I doing wrong? Any kind of help will be appreciated.
There are a few issues with this code, the first one being the naming of variables.
I suggest you choose more significative names in the future, because good naming is fundamental when someone else has to understand your code and your ideas.
Another thing is that the arguments of are in a counterintuitive order because the pair related to the array are separated by the index you want to look for.
I'd write int mediansearch(int A[], int size, int k)
Here the comparisons are reversed, k should be less than rather than greater than equal a
if (a <= k) // (k < a)
{
return mediansearch(S1, k, a);
}
else if (a + b <= k) // (k < a + b)
{
return A[ran];
}
else
{
return mediansearch(S3, k - a - b, c);
}
The other thing is that you're sharing S1, S2, and S3 among all the recursive calls and that causes some error that I wasn't able to identify, maybe someone commenting will help me out.
However, I suggest you read this article that explains in detail the procedure you're trying to implement: https://rcoh.me/posts/linear-time-median-finding/
It's python, but it can be easily ported to C/C++, and in fact that's what I did.
#include <iostream>
#include <stdlib.h>
#include <assert.h>
#include <time.h>
using namespace std;
int medianSearch(int A[], int size, int k)
{
int *lows = (int *)calloc(size, sizeof(int));
int lowsLen = 0;
int *highs = (int *)calloc(size, sizeof(int));
int highsLen = 0;
int *pivots = (int *)calloc(size, sizeof(int));
int pivotsLen = 0;
int median;
int pivot;
int i;
if (size == 1)
return A[0];
// Other ways of randomly picking a pivot
// pivot = 0;
// pivot = size-1;
// pivot = size/2;
assert(size > 0);
pivot = rand() % size;
for (i = 0; i < size; ++i)
{
if (A[i] < A[pivot])
{
lows[lowsLen] = A[i];
lowsLen++;
}
else if (A[i] > A[pivot])
{
highs[highsLen] = A[i];
highsLen++;
}
else
{
pivots[pivotsLen] = A[i];
pivotsLen++;
}
}
if (k < lowsLen)
median = medianSearch(lows, lowsLen, k);
else if (k < lowsLen + pivotsLen)
median = A[pivot];
else
median = medianSearch(highs, highsLen, k - lowsLen - pivotsLen);
free(lows);
free(highs);
free(pivots);
return median;
}
int compare(const void *a, const void *b)
{
return ( *(int *)a - *(int *)b );
}
int medianSorted(int A[], int size, int k)
{
qsort(A, size, sizeof(int), compare);
return A[k];
}
#define N 1000
int main()
{
int arr[N];
int brr[N];
int n = sizeof(arr) / sizeof(arr[0]);
int k = 200;
int x;
int y;
for (int i = 0; i < n; ++i)
arr[i] = brr[i] = rand();
x = medianSearch(arr, n, (k-1)%n);
y = medianSorted(brr, n, (k-1)%n);
string suffix;
switch (k % 10)
{
case 1: suffix = "st"; break;
case 2: suffix = "nd"; break;
case 3: suffix = "rd"; break;
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 0: suffix = "th"; break;
}
cout << k << suffix << " smallest is: " << x << endl;
cout << k << suffix << " smallest is: " << y << endl;
}
https://onlinegdb.com/HJc2V6Lbu

Searching Index of an Element from Array

I am stuck and a simple yet crazy search algorithm. I want to find the index of an element from an array calling a function. The problem is that although the element is already there, the function returns -1; which is supposed to return only if the element is not there.
This is the code:
#include <iostream>
using namespace std;
int search(int arr[], int size, int val, bool left) {
int res;
for (int i = 0; i < size; i++) {
if(val == arr[i]) {
res = i;
break;
}
else if(val != arr[i]) {
res = -1;
}
}
return -1;
}
int main() {
int arr[] = {1, 4, 6, 5, 2, 7, 10, 4};
int size = sizeof(arr) / sizeof(arr[0]);
cout << search(arr,size,6, true) << endl;
return 0;
}
Thanks in advance.
Try Return res from the function
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int search(int arr[], int size, int val, bool left) {
int res = -1;
for (int i = 0; i < size; i++) {
if(val == arr[i]) {
res = i;
break;
}
}
return res;
}
int main() {
int arr[] = {1, 4, 6, 5, 2, 7, 10, 4};
int size = sizeof(arr) / sizeof(arr[0]);
cout << search(arr,size,6, true) << endl;
return 0;
}
for (int i = 0; i < size; i++) {
if(val == arr[i]) {
res = i;
break;
}
else if(val != arr[i]) {
res = -1;
}
}
return -1;
You are returning -1 outside of for loop even when the element is present.
Initialize res variable above for loop and return it
res = -1
After for loop
return res

Find the index of the minimum element in a subarray

The function FindSubArrayMinimum is suppose to return the index of the minimum value in an array between the values (left,right). Instead of returning 1 as it should, it returns 7.
Here is my code:
#include <iostream>
using namespace std;
class Minimum {
int *array;
int arrayLen;
public:
Minimum(int *array, int arrayLen) {
}
void swap(int &a, int &b) {
int x;
x = a;
a = b;
b = x;
}
int findMinimum(int a, int b) {
if(a < b){
return a;
}else{
return b;
}
}
int findArrayMinimum(int a[], int arraySize) {
int min=a[0];
for(int i=0;i<arraySize-1;i++){
if(a[i] < min){
min = i;
}
}
return min;
}
int findSubArrayMinimum(int a[], int arraySize, int left, int right) {
int min = a[left];
for(int i=left;i<right+1;i++){
if(a[i] < min){
cout << min << endl;
min = i;
}
}
return min;
}
int findSubArrayMinimumAndSwap(int left, int right, int swapIndex) {
}
};
int main() {
int A[5] = {47, 7, 21, -1, 11};
Minimum min(A, 5);
cout << "Minimum of 7 and 11 is " << min.findMinimum(7, 11) << endl;
int x = 5, y = 7;
min.swap(x, y);
cout << "x = " << x << ", y = " << y << endl;
cout << "Minimum value is at position " << min.findArrayMinimum(A,5) << endl;
cout << "Minimum value between [1,2] is at position " <<
min.findSubArrayMinimum(A,5,1,2)<< endl;
return 0;
}
I cannot for the life of me figure out why it won't return the minimum index. Logically speaking it should work unless I'm missing something?
all of my other functions as all the ones I have finished I have working.
It is not true. In findArrayMinimum the loop should be
for(int i=0;i<arraySize;i++)
Or
for(int i=0;i<=arraySize-1;i++)
The initial value an the condition in the loop are also wrong. Should be int min=0 and if(a[i] < a[min])
Instead of returning 1 as it should, it returns 7.
findSubArrayMinimum is nice, except initial minimum value int min = a[left], should be int min = left and the condition in the loop should be if(a[i] < a[min]).
arraySize is odd in findSubArrayMinimum, it is not used.
Your do not need the separate implementation for findSubArray. You can do return findSubArrayMinimum(a, 0, arraySize - 1) in findSubArray.
If you would implement the tests with arrays of 0, 1, many elements, with the left, right, middle subarrays, you would discover all bugs in your code.
C++ is all about not re-inventing wheels.
#include <algorithm>
size_t findArrayMinimum(int a[], size_t arraySize) {
// Returns index of minimum element
return std::min_element(a, a + arraySize) - a;
}
In your findSubArrayMinumum you need min = a[i]; and not min = i; i is a index and a[i] is value.
I suggested you:
int findSubArrayMinimum(int a[], int arraySize, int left, int right) {
int index = left;
int min = a[left];
for(int i=left;i<right+1;i++){
if(a[i] < min){
min = a[min];
index = i;
}
}
return index;
}
int index = min.findSubArrayMinimum(A,5,1,3);
cout << "Minimum value between [1,2] is at position " << index <<
". and value is: " << A[index] << endl;
int findSubArrayMinimum(int a[], int arraySize, int left, int right) {
//The min is the index of minimum value since you are returning the index only
int min = left;
for(int i=left;i<=right;i++){
//since we have min = indexOfMin, then we need to compare the values
if(a[i] <= a[min]){
min = i;
}
}
//remember! You are returning the index of the minmum value!
return min;
}

Trying to debug and correct a function

#include <iostream>
#include <string>
using namespace std;
// Declaration of the function indexvalue()
int *maxArr(int [], const int);
// Another function used to print out an error message
void
problem(string str) {
cout << str << endl;
exit(1);
}
const int Size = 10;
int main()
{
int a[Size] = {23, 45, 12, 76, 9, 131, 10, 8, 23, 4};
int *b, i;
string error1("Problem with maxArr(), wrong subscript");
string error2("Problem with maxArr(), output should be NULL");
// Call the function multiple times with different input
// Note the use of pointer arithmetic
if (maxArr(a,Size)!= a+5) problem(error1);
if (maxArr(a,Size-5)!= a+3) problem(error1);
if (maxArr(a+6,4)!= a+8) problem(error1);
if (maxArr(a,0)!= NULL) problem(error2);
// The function passed all the tests
cout << "The function passed all the tests in this program\n" << endl;
exit(0);
}
int *maxArr(int arr[], int size){
int max = 0;
int index = 0;
if ( size < 0)
return NULL;
for (int i = 0; i < size; i++) {
if (arr[i] > max )
{
max = arr[i];
index = i;
}
return arr + i;
}
}
Specifications for maxArr()
The function accepts an integer array, and the number of elements as parameters.
The function returns the address of an int which points at the maximum value of the array.
i'm trying to figure out what's wrong with the maxArr() function and the only thing i've corrected so far is changing if(size < 0) to if (size <= 0) to handle the null case, I have no idea how to correct the function to account for the error1 message. Any help would be appreciated.
You have a brackets issue here:
for (int i = 0; i < size; i++) {
if (arr[i] > max )
{
max = arr[i];
index = i;
}
return arr + i;
}
Your return is within the for loop and therefore you will return on the first interation of the loop.
index is not used, you probably want to move the return statement outside the main loop and return arr + index;
You are returning from inside the for loop in the function maxArr. It will always return in the first iteration. Also you should return arr+index instead of arr+i.
for (int i = 0; i < size; i++)
{
if (arr[i] > max )
{
max = arr[i];
index = i;
}
//return arr + i;
// ^^^^ Wrong
}
return arr+index; //return from here
The check for returning NULL will fail with your current condition. You should check like this:
if ( size <= 0)
return NULL;