-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathC++
56 lines (47 loc) · 1.01 KB
/
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// C++ program for find the largest
// three elements in an array
#include <bits/stdc++.h>
using namespace std;
// Function to print three largest elements
void print3largest(int arr[], int arr_size)
{
int first, second, third;
// There should be atleast three elements
if (arr_size < 3)
{
cout << " Invalid Input ";
return;
}
third = first = second = INT_MIN;
for(int i = 0; i < arr_size; i++)
{
// If current element is
// greater than first
if (arr[i] > first)
{
third = second;
second = first;
first = arr[i];
}
// If arr[i] is in between first
// and second then update second
else if (arr[i] > second)
{
third = second;
second = arr[i];
}
else if (arr[i] > third)
third = arr[i];
}
cout << "Three largest elements are "
<< first << " " << second << " "
<< third << endl;
}
// Driver code
int main()
{
int arr[] = { 12, 13, 1, 10, 34, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
print3largest(arr, n);
return 0;
}