Find the second smallest element in an array
Given an array with n numbers, with n - 1 comparisons, we are able to find the smallest number in the array. After we find out the minimum number of the array, we only need n - 2 comparisons to find out the second smallest element in the array. Because there are n - 1 remaining elements.
Can we do better than this?
The answer is YES.
The algorithm works as follows. See the image below.
1) Split the array into groups of two.
2) Get the smaller one out of the two.
3) Keep comparing until we find out the minimum. There are n - 1 comparisons to find out the minimum of the array.
4) Note that the second smallest element is among the elements that were compared with the minimum in the comparison tree. There are lgn elements that are compare with the smallest element. See the double circled elements in the image. Now lgn -1 comparisons are needed to find the smallest value out of the lgn values.
Can we do better than this?
The answer is YES.
The algorithm works as follows. See the image below.
1) Split the array into groups of two.
2) Get the smaller one out of the two.
3) Keep comparing until we find out the minimum. There are n - 1 comparisons to find out the minimum of the array.
4) Note that the second smallest element is among the elements that were compared with the minimum in the comparison tree. There are lgn elements that are compare with the smallest element. See the double circled elements in the image. Now lgn -1 comparisons are needed to find the smallest value out of the lgn values.
The total comparisons are n - 1 + lgn - 1 = n + lgn - 2.

Comments
Post a Comment