Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 sort short array
In this article, we will learn to sort a short array in Java using the Arrays.sort() method. Begin by declaring and initializing an unsorted short array, then sort it and display the sorted array.
Arrays.sort() method : This method sorts the elements of array in ascending order which have specified range and specified order.
Syntax
public static void sort(Object[] a, int fromIndex, int toIndex)
Steps to sort short array
Following are the steps to sort short array in Java ?
- Declare and initialize an unsorted short array.
- Print the unsorted array.
- Use Arrays.sort() to sort the array.
- Print the sorted array.
Java program to sort short array
Below is the Java program to sort short array ?
import java.util.*;
import java.util.*;
public class Demo {
public static void main(String[] args) {
short[] arr = new short[] {
35,
25,
18,
45,
77,
21,
3
};
System.out.println("Unsorted:");
for (short s: arr) {
System.out.println(s);
}
System.out.println("Sorted:");
Arrays.sort(arr);
for (short s: arr) {
System.out.println(s);
}
System.out.println();
}
}
Output
Unsorted: 35 25 18 45 77 21 3 Sorted: 3 18 21 25 35 45 77
Code Explanation
Initialize an unsorted short array and print its elements. Use Arrays.sort() to sort the array in ascending order, then print the sorted array. The for-each loop is used to iterate through the array elements for displaying the elements.
Advertisements