- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to find the 2nd smallest number in an array
To find the 2nd smallest element of the given array, first of all, sort the array.
Sorting an array
- Compare the first two elements of the array
- If the first element is greater than the second swap them.
- Then, compare 2nd and 3rd elements if the second element is greater than the 3rd swap them.
- Repeat this till the end of the array.
After sorting an array print the 2nd element of the array.
Example
public class SmallestNumberInAnArray { public static void main(String args[]){ int temp, size; int array[] = {10, 20, 25, 63, 96, 57}; size = array.length; for(int i = 0; i<size; i++ ){ for(int j = i+1; j<size; j++){ if(array[i]>array[j]){ temp = array[i]; array[i] = array[j]; array[j] = temp; } } } System.out.println("2nd Smallest element of the array is:: "+array[0]); } }
Output
The 2nd Smallest element of the array is:: 10
Another solution
You can also sort the elements of the given array using the sort method of the java.util.Arrays class then, print the 2nd element of the array.
Example
import java.util.Arrays; public class LargestNumberSample { public static void main(String args[]){ int array[] = {10, 20, 25, 63, 96, 57}; int size = array.length; Arrays.sort(array); System.out.println("sorted Array ::"+Arrays.toString(array)); int res = array[1]; System.out.println("2nd smallest element is ::"+res); } }
Output
sorted Array ::[10, 20, 25, 57, 63, 96] largest element is ::20
- Related Articles
- Find the 2nd smallest number in a Java array.
- Java program to find the 2nd largest number in an array
- Java program to find the smallest number in an array
- Rearrange An Array In Order – Smallest, Largest, 2nd Smallest, 2nd Largest,. Using C++
- Find the 2nd largest number in a Java array.
- Java program to find Largest, Smallest, Second Largest, Second Smallest in an array
- Find the smallest number in a Java array.
- Program to Find the smallest number in an array of data in 8085 Microprocessor
- Find the 3rd smallest number in a Java array.
- Java program to find the largest number in an array
- Java program to find the 3rd largest number in an array
- C# Program to find the smallest element from an array
- Find the Smallest Positive Number Missing From an Unsorted Array
- 8085 Program to find the smallest number
- C program to find the second largest and smallest numbers in an array

Advertisements