search
HomeBackend DevelopmentC++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
arrayFindsecond 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

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 ); 
}

Output

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

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 ); 
}

Output

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

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 ); 
}

Output

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

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
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Debunking the Myths: Is C   Really a Dead Language?Debunking the Myths: Is C Really a Dead Language?May 05, 2025 am 12:11 AM

C is not dead, but has flourished in many key areas: 1) game development, 2) system programming, 3) high-performance computing, 4) browsers and network applications, C is still the mainstream choice, showing its strong vitality and application scenarios.

C# vs. C  : A Comparative Analysis of Programming LanguagesC# vs. C : A Comparative Analysis of Programming LanguagesMay 04, 2025 am 12:03 AM

The main differences between C# and C are syntax, memory management and performance: 1) C# syntax is modern, supports lambda and LINQ, and C retains C features and supports templates. 2) C# automatically manages memory, C needs to be managed manually. 3) C performance is better than C#, but C# performance is also being optimized.

Building XML Applications with C  : Practical ExamplesBuilding XML Applications with C : Practical ExamplesMay 03, 2025 am 12:16 AM

You can use the TinyXML, Pugixml, or libxml2 libraries to process XML data in C. 1) Parse XML files: Use DOM or SAX methods, DOM is suitable for small files, and SAX is suitable for large files. 2) Generate XML file: convert the data structure into XML format and write to the file. Through these steps, XML data can be effectively managed and manipulated.

XML in C  : Handling Complex Data StructuresXML in C : Handling Complex Data StructuresMay 02, 2025 am 12:04 AM

Working with XML data structures in C can use the TinyXML or pugixml library. 1) Use the pugixml library to parse and generate XML files. 2) Handle complex nested XML elements, such as book information. 3) Optimize XML processing code, and it is recommended to use efficient libraries and streaming parsing. Through these steps, XML data can be processed efficiently.

C   and Performance: Where It Still DominatesC and Performance: Where It Still DominatesMay 01, 2025 am 12:14 AM

C still dominates performance optimization because its low-level memory management and efficient execution capabilities make it indispensable in game development, financial transaction systems and embedded systems. Specifically, it is manifested as: 1) In game development, C's low-level memory management and efficient execution capabilities make it the preferred language for game engine development; 2) In financial transaction systems, C's performance advantages ensure extremely low latency and high throughput; 3) In embedded systems, C's low-level memory management and efficient execution capabilities make it very popular in resource-constrained environments.

C   XML Frameworks: Choosing the Right One for YouC XML Frameworks: Choosing the Right One for YouApr 30, 2025 am 12:01 AM

The choice of C XML framework should be based on project requirements. 1) TinyXML is suitable for resource-constrained environments, 2) pugixml is suitable for high-performance requirements, 3) Xerces-C supports complex XMLSchema verification, and performance, ease of use and licenses must be considered when choosing.

C# vs. C  : Choosing the Right Language for Your ProjectC# vs. C : Choosing the Right Language for Your ProjectApr 29, 2025 am 12:51 AM

C# is suitable for projects that require development efficiency and type safety, while C is suitable for projects that require high performance and hardware control. 1) C# provides garbage collection and LINQ, suitable for enterprise applications and Windows development. 2)C is known for its high performance and underlying control, and is widely used in gaming and system programming.

How to optimize codeHow to optimize codeApr 28, 2025 pm 10:27 PM

C code optimization can be achieved through the following strategies: 1. Manually manage memory for optimization use; 2. Write code that complies with compiler optimization rules; 3. Select appropriate algorithms and data structures; 4. Use inline functions to reduce call overhead; 5. Apply template metaprogramming to optimize at compile time; 6. Avoid unnecessary copying, use moving semantics and reference parameters; 7. Use const correctly to help compiler optimization; 8. Select appropriate data structures, such as std::vector.

See all articles

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),