How to Sort Array in Java
Here you will learn that How to sort array in java using 2 different ways.
What is Sorting?
Sorting is a method to arrange the data in either ascending or descending order. There are many sorting techniques available in java like Quick Sort, Insertion Sort, Bubble Sort, Merge Sort etc. For example:
Input: 2 5 3 7 5 9 1 4
Output: 1 2 3 4 5 7 9
Sort array in java without sort method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | //Sort Array in Java without sort method import java.util.*; public class ArraySorting { public static void main(String args[]) { int i,j, Largest, Smallest, tmp; Scanner sc = new Scanner(System.in); //Input how many elements System.out.print("Enter number of elements : "); int num=sc.nextInt(); int arr[]=new int[num]; // input Array elements System.out.print("Enter elements of array : "); for (i = 0; i < arr.length; i++) { arr[i] = sc.nextInt(); } //sorting in ascending order for (i = 0; i < arr.length; i++) { for(j = i + 1 ; j< arr.length; j++) { if(arr[i]>arr[j]) { tmp=arr[i]; arr[i]=arr[j]; arr[j]=tmp; } } } //print sorted array list for (i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } } |
Output
How to Sort array in java with sort method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | //Sort array in java with sort method import java.util.*; public class ArraySortMethod { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //Input how many elements System.out.print("Enter number of elements : "); int num=sc.nextInt(); int arr[]=new int[num]; // input Array elements System.out.print("Enter elements of array : "); for (int i = 0; i < arr.length; i++) { arr[i] = sc.nextInt(); } // Array sorting in ascending order Arrays.sort(arr); // Printing the sorted array System.out.println("Sorted array in ascending order:"); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } } |
Output
C:\CodeRevise\java>javac ArraySortMethod.java
C:\CodeRevise\java>java ArraySortMethod
Enter number of elements : 5
Enter elements of array : 4
3
6
2
1
Sorted array in ascending order:
1 2 3 4 6
Check out our other Java Programming Examples