forked from DSC-Banasthali-Vidyapith/Engineering-Daze
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Find the Third largest element in an array DSC-Banasthali-Vidyapith#12 …
…in JAVA Added Third_Largest_Element.java file to Arrays folder.
- Loading branch information
1 parent
3511fc4
commit 63054cd
Showing
1 changed file
with
63 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import java.util.*; | ||
|
||
class ThirdLargestElement | ||
{ | ||
|
||
//find the first, then second and then the third largest element. | ||
static void thirdLargestElement(int arr[]) | ||
{ | ||
|
||
int firstLargest = Integer.MIN_VALUE; | ||
for (int i = 0; i < arr.length ; i++) | ||
if (arr[i] > firstLargest) | ||
firstLargest = arr[i]; | ||
|
||
|
||
int secondLargest = Integer.MIN_VALUE; | ||
for (int i = 0; i < arr.length ; i++) | ||
if (arr[i] > secondLargest && arr[i] < firstLargest) | ||
secondLargest = arr[i]; | ||
|
||
|
||
int thirdLargest = Integer.MIN_VALUE; | ||
for (int i = 0; i < arr.length ; i++) | ||
if (arr[i] > thirdLargest && arr[i] < secondLargest) | ||
thirdLargest = arr[i]; | ||
|
||
System.out.println("Third Largest Element:: "+ thirdLargest); | ||
} | ||
|
||
// main method | ||
public static void main(String args[]) | ||
{ | ||
int len; | ||
Scanner sc=new Scanner(System.in); | ||
System.out.print("Enter the number of elements:: "); | ||
len=sc.nextInt(); | ||
int elements[] = new int[len]; | ||
System.out.println("Enter the elements of the array:: "); | ||
for(int i=0; i<len; i++) | ||
{ | ||
elements[i]=sc.nextInt(); | ||
} | ||
|
||
thirdLargestElement(elements); | ||
} | ||
} | ||
|
||
/*Test Cases | ||
Enter the number of elements:: | ||
5 | ||
Enter the elements of the array:: | ||
1 200 34 48 59 | ||
Third Largest Element:: 48 | ||
Enter the number of elements:: | ||
7 | ||
Enter the elements of the array:: | ||
9 8 13 15 21 98 50 | ||
Third Largest Element:: 21 | ||
*/ | ||
|