FOR FREE MATERIALS

2nd largest element from the array

Back to Programming

Description

The array of elements is taken as input. This program finds the 2nd largest element from the array. First, the largest element is found out from the array. Then the element is searched which is maximum among the rest of the elements of the array (except the first largest element). That is the 2nd largest element of the array.

 

Algorithm

INPUT: Array elements
OUTPUT: the 2nd largest element of the array
PROCESS:
Step 1: [taking the input]
	Read n [number of elements]
	For i=0 to n-1 repeat
		Read a[i]
	[end of ‘for’ loop]
Step 2: [finding the 2nd largest element]
	Set max<-a[0]
	For i=0 to n-1 repeat
		If a[i]>max then
			Set max<-a[i]
		[End of ‘if’]
[End of ‘for’ loop]
	Set max2<--32767
	For i=0 to n-1 repeat
		If a[i]=max then
			Continue
		[End of ‘if’]
		if a[i]>max2 then
			Set max2<-a[i]
		[End of ‘if’]
	[End of ‘for’ loop]
Step 3: Stop.

Code

Complexity: