Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

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

public class SecondSmallest {
	/*
	 * Aim is to find second smallest
	 * element in an array in an efficient
	 * manner.
	 */
	public static void main(String[] args) {
		int[] arr1 = { 1 };
		int secondSmallest = get2ndSmallest(arr1);
		// Below prints: Size should be greater than 2.
		if (secondSmallest == Integer.MAX_VALUE) {
			System.out.println("Size should be" +
					" greater than 2.");
		} else {
			System.out.println(secondSmallest);
		}
		int[] arr2 = { 1, 2, 4, 2 };
		secondSmallest = get2ndSmallest(arr2);
		// Below prints: 2.
		if (secondSmallest == Integer.MAX_VALUE) {
			System.out.println("Size should be" +
					" greater than 2.");
		} else {
			System.out.println(secondSmallest);
		}
	}

	// Supporting method for finding 2nd
	// smallest value in array.
	private static int get2ndSmallest(int[] arr) {
		int smallest = Integer.MAX_VALUE;
		int secondSmallest = Integer.MAX_VALUE;
		for (int num : arr) {
			// Update second smallest if
			// a new running min is found
			if (num < smallest) {
				secondSmallest = smallest;
				smallest = num;
			} else if (num < secondSmallest &&
					num != smallest) {
				secondSmallest = num;
			}
		}
		return secondSmallest;
	}
}
Comment

PREVIOUS NEXT
Code Example
Java :: Java make numbers 
Java :: java mp3 player 
Java :: who created java 
Java :: arrays.tostring java 
Java :: java list distinct by key 
Java :: frequency of each element from list in java 
Java :: how to get data from combobox in java 
Java :: input array in String in java 
Java :: java method return list 
Java :: arraylist items into string 
Java :: how to check if string is double or not in java 
Java :: how to print to the console in java 
Java :: running sum of 1d array leetcode 
Java :: responseentity spring boot 
Java :: declaration of double array in java 
Java :: get the image from camera click in android 
Java :: Right triangle star pattern in java 
Java :: ternary operator in java for null check 
Java :: uninstall java ac 
Java :: declare array of chars java 
Java :: count occurrences of character in string java 8 
Java :: java string array to one string 
Java :: java print statement 
Java :: java hash password 
Java :: docker java image 
Java :: worldedit api paste schematic 
Java :: Concept of Association in java 
Java :: android studio edittext enter pressed 
Java :: camera permission in android 
Java :: multiplication program java 
ADD CONTENT
Topic
Content
Source link
Name
4+9 =