How to find index of largest element in an array C++

Finding the index of the largest element in an unsorted array is done through brute force search. If the array is sorted the task is trivial and the index is the length-1 if it’s sorted in ascending order and is 0 otherwise. Therefore, this article covers only the version of the unsorted array.

Using for loop:

The principle behind this method is looping through the entire array and storing the pointer to the maximum element in a pointer variable. If an element is found to be greater than the one pointed by the pointer variable then the pointer variable is updated to point to this larger element.

Check out this article on how to loop over an array for further information.

The following code illustrates this method on an array of integers:

#include <iostream>
int main()
{
  int a[10];
  std::cout << "Enter 10 elements: ";
  for (int i = 0; i < 10; i++)
  {
    std::cin >> a[i];
  }
  int* max=a; //larger element pointer initially pointed to first element
  for (int i = 1; i < 10; i++)
  {
    if (a[i] > *max)
    {
      max = &a[i]; //updating the pointer to maximum 
    }
    }
  int index = max - a; //pointer arithmetic to obtain the index
  std::cout << "The largest index is " << index << "\n";
}

 

Output:
Enter 10 elements: 1 5 98 60 -8 4 89 63 100 4 
The largest index is 8 

Using STL algorithm:

The STL of C++ provides an algorithm that works similarly to the above method that we discussed. However, this can be used on almost every data structure interface provided by the STL. Using this method can reduce code and enhance readability.

The function used to find an iterator (pointer in this case) to the largest element in a range is the std::max_element() function.

Although this function has many optional parameters we shall only consider the essential parameters which are the pointer to the first and last element.

The following code illustrates the point:

#include <iostream>
int main()
{
  const int n = 10;
  int a[n];
  std::cout << "Enter 10 elements: ";
  for (int i = 0; i < n; i++)
  {
    std::cin >> a[i];
  }
  int* max=a; //larger element pointer initially pointed to first element
  max=std::max_element(a, a + n);
  int index = max - a;
  std::cout << "Index of largest element is: " << index << "\n";
}

Output is the same as the above code.

Leave a Reply

Your email address will not be published. Required fields are marked *