Finding the Position of the Maximum Element

Finding the position of the maximum element

In the STL, std::max_element provides the iterator (which can be used to get index with std::distance, if you really want it).

int main(int argc, char** argv) {
int A[4] = {0, 2, 3, 1};
const int N = sizeof(A) / sizeof(int);

cout << "Index of max element: "
<< distance(A, max_element(A, A + N))
<< endl;

return 0;
}

How to find all positions of the maximum value in a list?

>>> m = max(a)
>>> [i for i, j in enumerate(a) if j == m]
[9, 12]

Getting the index of the returned max or min item using max()/min() on a list

if is_min_level:
return values.index(min(values))
else:
return values.index(max(values))

Print the maximum element with their index position

You can find the max value and check the array for it e.g.

int[] a = {10, 20, 30, 40, 40};
int max = Arrays.stream(a).max().getAsInt();
for (int i = 0; i < a.length; i++) {
if (a[i] == max) {
System.out.print(max + " " + i);
}
}

Divide and conquer algorithm to find position of max element

You can return a std::pair which contains both the array value & position.

#include <iostream>
#include <utility>
using namespace std;

std::pair<int, 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], l};
}
int m = (l + r) / 2;
auto up = maxElement(a, l, m);
auto vp = maxElement(a, m, r);
return up.first > vp.first ? up : vp;
}

/* 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]);
auto result = maxElement(Arr, 0, arrSize);
cout << result.first << ", l = " << result.second << endl;
return 0;
}

Calculates the position of the max element for array. function returns the max element. pass the array by the pointer and the pos. by the reference

Sure we can help you a little bit. But the whole topic of pointers and references cannot be covered in a short answer here on SO. You need to read a book.

The following will be very simplified and there is much more in reality. But let's start with this simple explanantion.

Let me give you a typical example that is often used in C or very early C++ books. Look at the function swap that should exchange the values of 2 variables.

#include <iostream>

void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}

int main() {
int a = 1, b = 2;
swap(a, b);
std::cout << "a: " << a << "\tb: " << b << '\n';
}

We hope that after the call to the function swap, "a" will contain 2 and "b" will be 1. But it is not. Because in this case (and per default) the variables that are given to the function swap, are passed by value. So, the compiler will generate some code and copies the value of variables "a" and "b" into some local internal storage, also accessible with the name "a" and "b". So, the original "a" and "b" will never be touched or modified. By passing a variable by value, a copy will be mdae. This is often intended, but will not work in this example.

The next development stage was the pointer. The pointer is also a variable that contains a value. But this time it is the address of another variable somehwere in memory. If you have a variable like int a=3; then the 3 is somewhere stored in memory (decided by the compiler of the linker) and you can access the memory region with the name "a".

A pointer can store the memory address of this variable. So not the value 3 of the variable "a", but the address of the variable "a" in memory. The pointer points to that memory region, where the 3 ist stored. If you want to access this value, then you need to dereference the pointer with the * operator. And to get the address of variable 'a', you can write &a. But how does this help?

It helps you indirectly to get modified or result values out of a function. Example:

#include <iostream>

void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

int main() {
int a = 1, b = 2;
swap(&a, &b);
std::cout << "a: " << a << "\tb: " << b << '\n';
}

In main we take the address of variable "a" and "b" and give this to the function. The address of the function (the pointer) will be given to the function as value now. A copy of the pointer will be made (not in reality) but this does not harm, because we can now modify the original values of the variable, by derefencing the pointer. Then the function ends and we will find the correct values in the original variables "a" and "b".

But, pointers are notoriously difficult to understand and very error prone. Therefore the "reference" has been invented. It is kind of an alias for a normal variable. And the good point is that if you pass a reference to the function, then you can modify immediately the original value. That makes things very convenient.

The function swap could then be written as

#include <iostream>

void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}

int main() {
int a = 1, b = 2;
swap(a, b);
std::cout << "a: " << a << "\tb: " << b << '\n';
}

And this gives the intented result. And is by far simpler.


Now to your code. First, VLAs (variable length arrays), namely the int tab[n]; where 'n' is no compile time constant, are a not a ppart of the C++ language. You canot use them. You could and should use a std::vector instead, but you did not yet learn about it. So we will use new, to allocate some memory dynamically. Please note: In reality, new, raw pointers for owned memory and C-Style arrays should not be used. But anyway.

Then let us look at your requirements

function returns the max element. pass the array by the pointer and the pos. by the reference

So, we need a function to calculate the max element in an array, then return this value, and additionally copy the position of the max element in a variable, given to the function as reference. We will add an additional parameter for the size of the array, because we will not use VLAs here. The array will be given by pointer.

So the prototype of your function will be:

int getMaxElement(int *array, int sizeOfArray, int& positionOfMaxValue)

To implement such a function, we create an internal variable to hold the max value, which we will later return. Then, we compare all values in a loop against this max value and, if we find a bigger one, then we store this new result. As the initial value, we can simply take the first value of the array.

Example:

#include <iostream>

int getMaxElement(int* array, int sizeOfArray, int& positionOfMaxValue) {
int resultingMaxValue = 0;
if (sizeOfArray > 0) {
resultingMaxValue = array[0];

for (int i = 0; i < sizeOfArray; ++i) {
if (array[i] > resultingMaxValue) {
resultingMaxValue = array[i];
positionOfMaxValue = i;
}
}
}
return resultingMaxValue;
}

int main() {
// Get array size from user
std::cout << "\nPlease enter the array size: ";
int arraySize = 0;
std::cin >> arraySize;

// Create an array
int* array = new int[arraySize];

// Read all values into the array
for (int i = 0; i < arraySize; ++i)
std::cin >> array[i];

// Now calculate the max value and position of the max value
int position = 0;
int maxValue = getMaxElement(array, arraySize, position);

// Show result
std::cout << "\n\nResult:\nThe maximum value '" << maxValue << "' is at position " << position << '\n';

delete[] array;
}

Please remember: This is a very simplified explanation

Find the position of the k-largest element in max-heap

The 6th-largest element can be much farther out. The extreme case is where the first six elements are the root and a series of right-children. Each child is at node 2n+1, where n is the parent's node. The sequence of indices for the right-most sequence is 1, 3, 7, 15, 31, 63 (a.k.a. 2^6-1). Other, smaller values fill in the left side of each branch.

The earliest position is if that same value happened to be the left-child of the root, while all of the others went to the right branch: it appears in location 2. Again, smaller values appear as needed.

So, the range of possible values is from 2 to 2^n-1.
Your remaining problem is to determine which of the remaining locations can contain that 6th-largest element.

Draw a tree of the proper depth -- better yet, do this only 4 levels deep, and work with the 4th-largest element. Say, use 99, 98, 98, 96, and then the "other" values can be 1 through 11. Is there anywhere on this tree you can put 96 that you cannot arrange the other numbers to form a legal tree?

Expand the tree one more level. Now where are the holes in which you cannot put 96?

Does that get you un-stuck?



Related Topics



Leave a reply



Submit