Majd Khoury - 3 months ago 19

Java Question

We are required in our assignment to find the second smallest integer in one array recursively. However, for the sake of understanding the subject more, I want to do it iteratively first (with the help of this website) and recursively on my own.

Unfortunately, doing it iteratively is quite confusing. I understand that the solution is simple but i can't wrap my head around it.

Below is 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 works for a few numbers, but not all. The numbers change around because the inner if condition isn't as efficient as the outer if condition.

Array rearrangements are forbidden.

Answer

Try this one. Second condition is used to catch an event when the smallest number is the first

```
int[] elements = {-5, -4, 0, 2, 10, 3, -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, -4, 0, 2, 10, 3, -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];
}
}
```