Table of Contents
Understand concepts through examples
algorithm
Example
Output
Use double traversal
Use single traversal
in conclusion
Home Backend Development C++ C++ program to find the second largest element in an array

C++ program to find the second largest element in an array

Sep 15, 2023 pm 10:45 PM
array Find second element

C++ program to find the second largest element in an array

The purpose of an array is to store similar types of data in a series of memory locations that can be accessed using base addresses and indexes. We use arrays in many different applications to hold data for various purposes. Finding the smallest and largest elements is a fairly common example of arrays, which are needed in several applications including sorting, etc. In this article, we will learn how to find the second largest element from an array in C.

Understand concepts through examples

Given array A = [89, 12, 32, 74, 14, 69, 45, 12, 99, 85, 63, 32]
The second largest element is 89
Copy after login

In the above example, there are 12 elements in the array. The largest element in the array is 99, and the second largest element is 89. In the first method, to find the second largest element, we only need to sort the elements in ascending or descending order, and then directly return the second to last or second element to obtain the second largest element. The algorithm is as follows -

algorithm

  • Get an array A

  • of size n
  • Sort array A according to the non-increasing order of the values ​​​​of array A

  • Return A[ 1 ] // Because the 0th index contains the largest element

Example

#include <iostream>
#include <algorithm>
# define Z 30

using namespace std;

void displayArr(int arr[], int n ) {
   for( int i = 0; i < n; i++ ){
      cout << arr[ i ] << ", ";
   } 
   cout << endl;
} 

int getSecondLargest( int A[], int n ){
   sort( A, A + n, greater<int>() );
   return A[ 1 ];
}

int main() {
   int arr[ Z ] = {84, 56, 21, 32, 74, 96, 85, 41, 21, 94, 20, 37, 36, 75, 20};
   int n = 15;
   
   cout << "Given array elements: ";
   displayArr( arr, n);
   
   cout << "The second largest element: " << getSecondLargest( arr, n ); 
}
Copy after login

Output

Given array elements: 84, 56, 21, 32, 74, 96, 85, 41, 21, 94, 20, 37, 36, 75, 20, 
The second largest element: 94
Copy after login
Copy after login
Copy after login

Use double traversal

The above method seems simple, but this process is not efficient for this problem. Since we are using sorting, performing the sorting takes at least O(n.log n) time. But we can also solve this problem in linear time. In the current method, we iterate through the array of elements twice and find the second largest element. Let's check the algorithm.

algorithm

  • Get an array A

  • of size n
  • Maximum := -infinity

  • Maximum seconds := -infinity

  • For each element e in A, execute

    • If e is greater than Maximum, then

      • Max=e

    • End if

  • Finish

  • For each element e in A, execute

    • If e is greater than secLargest but less than maximum, then

      • Second maximum = e

    • End if

  • Finish

  • Return the maximum number of seconds

Example

#include <iostream>
#include <algorithm>
# define Z 30

using namespace std;

void displayArr(int arr[], int n ) {
   for( int i = 0; i < n; i++ ){
      cout << arr[ i ] << ", ";
   } 
   cout << endl;
} 

int getSecondLargest( int A[], int n ){
   int largest = -99999;
   for( int i = 0; i < n; i++ ) {
      if( A[i] > largest ){
         largest = A [ i ]; 
      }   
   }
   int secLargest = -99999;
   for( int i = 0; i < n; i++ ) {
      if( A[i] > secLargest && A[i] < largest ){
         secLargest = A [ i ]; 
      }   
   }
   return secLargest;
}

int main() {
   int arr[ Z ] = {84, 56, 21, 32, 74, 96, 85, 41, 21, 94, 20, 37, 36, 75, 20};
   int n = 15;
   
   cout << "Given array elements: ";
   displayArr( arr, n);
   
   cout << "The second largest element: " << getSecondLargest( arr, n ); 
}
Copy after login

Output

Given array elements: 84, 56, 21, 32, 74, 96, 85, 41, 21, 94, 20, 37, 36, 75, 20, 
The second largest element: 94
Copy after login
Copy after login
Copy after login

Use single traversal

The above solution iterates through the array twice. In the first run, find the largest element from the array, then in the second run, search for the largest element that is not larger than the first largest. Since the array is a linear data structure, each traversal takes O(n) time, so the final solution time is O(2n), which is also linear, similar to O(n). But this is not an efficient solution, we can only solve this problem with one pass. Let's see its algorithm.

algorithm

  • Get an array A

  • of size n
  • Maximum := A[0]

  • For starting index from 1 to n - 1, execute

    • If the current element A[i] is greater than maximum, then

      • Second maximum := maximum

      • Maximum := A[ i ]

    • Otherwise when A[ i ] is between largest and secLargest, then

      • Maximum seconds := A[ i ]

    • End if

  • Finish

  • Return the maximum number of seconds

Example

#include <iostream>
#include <algorithm>
# define Z 30

using namespace std;

void displayArr(int arr[], int n ) {
   for( int i = 0; i < n; i++ ){
      cout << arr[ i ] << ", ";
   } 
   cout << endl;
} 

int getSecondLargest( int A[], int n ){
   int largest = A[ 0 ];
   int secLargest = -9999;
   for( int i = 1; i < n; i++ ) {
      if( A[i] > largest ){
         secLargest = largest; 
         largest = A[ i ];
      }   
      else if( secLargest < A[ i ] && A[ i ] != largest ) {
         secLargest = A[ i ];
      }
   } 
   return secLargest;
}

int main() {
   int arr[ Z ] = {84, 56, 21, 32, 74, 96, 85, 41, 21, 94, 20, 37, 36, 75, 20};
   int n = 15;
   
   cout << "Given array elements: ";
   displayArr( arr, n);
   
   cout << "The second largest element: " << getSecondLargest( arr, n ); 
}
Copy after login

Output

Given array elements: 84, 56, 21, 32, 74, 96, 85, 41, 21, 94, 20, 37, 36, 75, 20, 
The second largest element: 94
Copy after login
Copy after login
Copy after login

in conclusion

In this article, we learned about three different ways to find the second largest element from a given array. The first method is to use sorting. However, this solution is not efficient and takes at least O(n log n ) time. The latter solutions are very efficient since they require linear time. The second solution is to use a double pass over the array, which can also be optimized with a single pass as shown in the third solution.

The above is the detailed content of C++ program to find the second largest element in an array. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to remove duplicate elements from PHP array using foreach loop? How to remove duplicate elements from PHP array using foreach loop? Apr 27, 2024 am 11:33 AM

The method of using a foreach loop to remove duplicate elements from a PHP array is as follows: traverse the array, and if the element already exists and the current position is not the first occurrence, delete it. For example, if there are duplicate records in the database query results, you can use this method to remove them and obtain results without duplicate records.

The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy May 01, 2024 pm 12:30 PM

Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization.

PHP array key value flipping: Comparative performance analysis of different methods PHP array key value flipping: Comparative performance analysis of different methods May 03, 2024 pm 09:03 PM

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values ​​takes a relatively long time.

Application of PHP array grouping function in data sorting Application of PHP array grouping function in data sorting May 04, 2024 pm 01:03 PM

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Apr 30, 2024 pm 03:42 PM

The best practice for performing an array deep copy in PHP is to use json_decode(json_encode($arr)) to convert the array to a JSON string and then convert it back to an array. Use unserialize(serialize($arr)) to serialize the array to a string and then deserialize it to a new array. Use the RecursiveIteratorIterator to recursively traverse multidimensional arrays.

PHP array multi-dimensional sorting practice: from simple to complex scenarios PHP array multi-dimensional sorting practice: from simple to complex scenarios Apr 29, 2024 pm 09:12 PM

Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price.

The role of PHP array grouping function in finding duplicate elements The role of PHP array grouping function in finding duplicate elements May 05, 2024 am 09:21 AM

PHP's array_group() function can be used to group an array by a specified key to find duplicate elements. This function works through the following steps: Use key_callback to specify the grouping key. Optionally use value_callback to determine grouping values. Count grouped elements and identify duplicates. Therefore, the array_group() function is very useful for finding and processing duplicate elements.

PHP array merging and deduplication algorithm: parallel solution PHP array merging and deduplication algorithm: parallel solution Apr 18, 2024 pm 02:30 PM

The PHP array merging and deduplication algorithm provides a parallel solution, dividing the original array into small blocks for parallel processing, and the main process merges the results of the blocks to deduplicate. Algorithmic steps: Split the original array into equally allocated small blocks. Process each block for deduplication in parallel. Merge block results and deduplicate again.

See all articles