Java – finds the second smallest integer in the array
•
Java
In our assignment, we need to recursively find the second smallest integer in an array However, in order to better understand this topic, I want to do it iteratively (with the help of this website) and recursively myself
Unfortunately, executing it iteratively is very confusing I know the solution is simple, but I can't solve it
Here's my code, so far:
public static void main(String[] args) { int[] elements = {0,2,10,3,-3 }; int smallest = 0; int secondSmallest = 0; for (int i = 0; i < elements.length; i++) { for (int j = 0; j < elements.length; j++) { if (elements[i] < smallest) { smallest = elements[i]; if (elements[j] < secondSmallest) { secondSmallest = elements[j]; } } } } System.out.println("The smallest element is: " + smallest + "\n"+ "The second smallest element is: " + secondSmallest); }
This applies to some numbers, but not all The number changes because the internal if condition is not as valid as the external if condition
Array rearrangement is prohibited
Solution
Try this When the minimum number is the first, the second condition is used to capture the event
int[] elements = {-5,-4,-3}; int smallest = Integer.MAX_VALUE; int secondSmallest = Integer.MAX_VALUE; for (int i = 0; i < elements.length; i++) { if(elements[i]==smallest){ secondSmallest=smallest; } else if (elements[i] < smallest) { secondSmallest = smallest; smallest = elements[i]; } else if (elements[i] < secondSmallest) { secondSmallest = elements[i]; } }
UPD by @Axel
int[] elements = {-5,-3}; int smallest = Integer.MAX_VALUE; int secondSmallest = Integer.MAX_VALUE; for (int i = 0; i < elements.length; i++) { if (elements[i] < smallest) { secondSmallest = smallest; smallest = elements[i]; } else if (elements[i] < secondSmallest) { secondSmallest = elements[i]; } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码