Sep 3, 2024
In this tutorial, we discuss how to find the second smallest number in an array using two different approaches.
[-1, 7, 1, 18, 34]
Sorting Method
1
after sorting.[-1, 7, 1, 18, 34]
results in [-1, 1, 7, 18, 34]
.1
(element at index 1
).Time Complexity
Limitation
[-1, -1, 1, 18, 34]
), the result may be incorrect.Traversal Method
smallest
and second_smallest
, initialized to Integer.MAX_VALUE
.Algorithm Steps
0
of the array.smallest
, update second_smallest
to be smallest
and then update smallest
to the current element.smallest
and smaller than second_smallest
, update second_smallest
to the current element.Example Walkthrough
[-1, 7, 1, 18, 34]
:
smallest = Integer.MAX_VALUE
, second_smallest = Integer.MAX_VALUE
.-1
: smallest = -1
, second_smallest = Integer.MAX_VALUE
.7
: second_smallest = 7
.1
: second_smallest = 1
.1
.Time Complexity
Why Use Integer.MAX_VALUE
Integer.MAX_VALUE
ensures that any element in the array will be less than the initial values of smallest
and second_smallest
, allowing for proper comparisons.0
or negative values were used as initial values, incorrect results could arise if the smallest number in the array is less than the assigned initial value.// Example method to find second smallest number
public static int findSecondSmallest(int[] arr) {
int smallest = Integer.MAX_VALUE;
int second_smallest = Integer.MAX_VALUE;
for (int i = 0; i < arr.length; i++) {
if (arr[i] < smallest) {
second_smallest = smallest;
smallest = arr[i];
} else if (arr[i] > smallest && arr[i] < second_smallest) {
second_smallest = arr[i];
}
}
return second_smallest;
}