I am trying to find the index of the max element in an array using a divide and conquer algorithm. Currently, the output is correctly outputting the maximum value of my array, but I cannot figure out how to pass the position of that maximum element.
#include <iostream>
using namespace std;
int maxElement(int a[], int l, int r) {
if(r - l == 1) {
cout << "R - L == 1 " << "Array value: " << a[l] << " Pos: " << l << endl;
return a[l];
}
int m = (l + r) / 2;
int u = maxElement(a, l, m);
int v = maxElement(a, m, r);
return u > v ? u : v;
}
/* Driver program to test above functions */
int main() {
int Arr[] = {1, 4, 9, 3, 4, 9, 5, 6, 9, 3, 7};
int arrSize = sizeof(Arr)/sizeof(Arr[0]);
cout << maxElement(Arr, 0, arrSize) << endl;
return 0;
}
maxElementreturn an index instead of a value.a[l]you can returnl. Anduandvbecomes the indexes of max element. You can compare and returna[u]>a[v]?u:vforloop. Nor recursion required.