Find Second Smallest Number in an Array : Java Code

preview_player
Показать описание
Write a java program to find second smallest number in an array in O(n) time complexity. In this tutorial, I have explained how to find second smallest number in an array without sorting.

Рекомендации по теме
Комментарии
Автор

Thank you for this tutorial i have a question. if i use int[] arr={5, 4, 2, 6, 1}; this returns 6, but it has to be 2. i could't figure out what is wrong.

seydaozdemir
Автор

Arrays.sort(arr);
for (int i = 0; i < arr.length; i++) {
if(arr[i] == arr[i+1]) {

}else {
System.out.println("The second smallest number in the array is: "+ arr[i+1]);
break;
}
}
I think that's better solution or is it faulty?

crollex
Автор

Code link is present in the description box

ProgrammingTutorialsM
Автор

This aproch is wrong if we use array {2, 5, 6, 7, 8, 1, 4}; then we get 4 insted of 2

kiransawant
Автор

int[] a ={5, 4, 2, 9, 1}; doesnt work for this array

suchitrapal
Автор

A better if else could've been:
min1 = A[0]; min2 = A[0]

for i in range(len(A)):
if A[i] < min1:
min1, min2 = A[i], min1
elif A[i] < min2:
min2 = A[i]
print(min2)

weirdprogrammer
Автор

We can just sort the array first and then assign arr[ 1 ] = second smallest element

asimgiri
Автор

if we take {1, 2, 1, -1}...its giving second smallest as 2 .. it must be 1

sumitsahu