Second smallest number in array

Hello, I have this txt file
1
2
3
4
5
12.5
17.69
458.2
4892.3
7.02

And I need to find second smallest number in array, how I need to do it?
1
2
3
4
5
6
double min=0.0, min2;
[code]for(int i=0; i<n; i++){
if(S[i]<min){
min=S[i];
}
}


1
2
3
4
5
for(int i=0; i<n; i++)[
if(min<S[i] && S[i]>min2){
min2=S[i];
}
}
Last edited on
Find the smallest first, then find the smallest again, but this time with the condition that this new smallest must be larger than the previous smallest.

1
2
3
4
float arr[5] = {1.f, 4.f, 0.5f, 3.f, 0.3f};
float *f = std::min_element(arr, arr + 5, [](const float &a, const float &b) -> bool {return a < b;});
float *s = std::min_element(arr, arr + 5, [f](const float &a, const float &b) -> bool {return a < b && a > *f;});
std::cout << *s << std::endl;
Ok, thanks, but this is too much compicated for me. I don't know what is float and so on, because I'm just beginner. It is possible to write this code without float and so on ->?
Last edited on
Just change your initial values for min and min2 to very large values (larger than the largest possible value in the list).

Also, you need the following change.
1
2
3
4
5
for(int i=0; i<n; i++)[
if(min<S[i] && S[i]<min2){ // not S[i] > min2
min2=S[i];
}
}


Last edited on
float is a half-precision double. Here is an implementation using more elementary functionality.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
double arr[5] {1., 4., 0.5, 3., 0.3};
double smallest = arr[0], secondsmallest = arr[0];

for (double &x : arr)
{
    if (x < smallest)
        smallest = x;
}

for (double &x : arr)
{
    if (x < secondsmallest && x > smallest)
        secondsmallest = x;
}

std::cout << secondsmallest << std::endl;


Perhaps you should read http://www.cplusplus.com/doc/tutorial/variables/
@Bourgond Aries

Nice code! One minor point.
I think the initial value for secondsmallest should be a very large number. If arr[0] is the smallest number in the array, then the value of secondsmallest will not change ever.
@abhishekm71

Indeed, you are right. I stand corrected. I have implemented your advice.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
double arr[6] {0.2, 1., 4., 0.5, 3., 0.3};
double smallest = arr[0], secondsmallest = std::numeric_limits<double>::max();

for (double &x : arr)
{
    if (x < smallest)
        smallest = x;
}

for (double &x : arr)
{
    if (x < secondsmallest && x > smallest)
        secondsmallest = x;
}

std::cout << secondsmallest << std::endl;
Topic archived. No new replies allowed.