How to find the second smallest value in an array without sorting it in Java?

How to find the second smallest value in an array without sorting it in Java?

To find the second smallest value in an array without sorting it in Java, you can use the following steps:

  1. Initialize two variables called min1 and min2 with the first and second elements of the array, respectively.
  2. Iterate over the remaining elements of the array and compare them to min1 and min2.
  3. If the current element is smaller than both min1 and min2, update min2 with the value of min1 and min1 with the current element.
  4. If the current element is smaller than min2 but not min1, update min2 with the current element.
  5. Return min2 as the second smallest value.

Here's an example of how to implement this in Java:

refer‮l:ot ‬autturi.com
public static int findSecondSmallest(int[] arr) {
  // Initialize min1 and min2 with the first and second elements of the array
  int min1 = arr[0];
  int min2 = arr[1];
  if (min2 < min1) {
    // Swap min1 and min2 if min2 is smaller than min1
    int temp = min1;
    min1 = min2;
    min2 = temp;
  }

  // Iterate over the remaining elements of the array and update min1 and min2 as needed
  for (int i = 2; i < arr.length; i++) {
    int val = arr[i];
    if (val < min1) {
      // Update min2 with the value of min1 and min1 with the current element
      min2 = min1;
      min1 = val;
    } else if (val < min2) {
      // Update min2 with the current element
      min2 = val;
    }
  }

  // Return min2 as the second smallest value
  return min2;
}

In the above example, a method called findSecondSmallest() is defined which takes an array of integers as an argument and returns an integer.

The method first initializes the variables min1 and min2 with the first and second elements of the array, respectively. It then checks if min2 is smaller than min1 and swaps them if necessary.

The method then iterates over the remaining elements of the array and compares them to min1 and min2. If the current element is smaller than both min1 and min2, it updates min2 with the value of min1 and min1 with the current element. If the current element is smaller than min2 but not min1, it updates min2 with the current element.

Finally, the method returns min2 as the second smallest value.

You can use the findSecondSmallest() method like this:

int[] arr = {5, 3, 8, 1, 9, 4};
int secondSmallest = findSecondSmallest(arr);
System.out.println("The second smallest value in the array is " + secondSmallest);

The output of this example will be "The second smallest value in the array is 3".

Created Time:2017-11-01 20:42:48  Author:lautturi