-
Notifications
You must be signed in to change notification settings - Fork 2
/
find_smallest_second_smallest_arr.cpp
72 lines (55 loc) · 1.63 KB
/
find_smallest_second_smallest_arr.cpp
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/****************************************************************************
File name: find_smallest_second_smallest_arr.cpp
Author: babajr
*****************************************************************************/
/*
Program to get the smallest and second smallest element
in the array.
Input: arr = [4,1,3,10,12,1]
Output: 12, 10
*/
#include<bits/stdc++.h>
using namespace std;
/*
API to get the smallest elemenet and second smallest element in the array.
Algo:
--> BRUTE FORCE
--> sort the array in the ascending order
--> first and second element are the smallest and second smallest.
--> Efficient Solution
--> first = second = MAX_VAL
--> traverse the array,
if(arr[i] < first), update second and first
else if(arr[i] < second), update second
*/
void find_smallest_second_smallest(int arr[], int size)
{
int first = INT_MAX;
int second = INT_MAX;
if(size < 2) // array must contain atleast 2 elements.
return;
for(int i = 0; i < size; i++)
{
if(arr[i] < first)
{
second = first;
first = arr[i];
}
// second condition for duplicate elements
else if(arr[i] < second && arr[i] != first)
{
second = arr[i];
}
}
if(second == INT_MAX) // array may contain same element multiple times
printf("Second Smallest element not found\n");
else
printf("Smallest : %d and Second Smallest : %d\n", first, second);
}
int main(void)
{
int arr[] = {4,1,3,10,12,1};
int size = sizeof(arr) / sizeof(arr[0]);
find_smallest_second_smallest(arr, size);
return 0;
}