Sort array in ascending order Java
In this post, you will learn how to sort an array in ascending order using the Java programming such that elements will be arranged from smallest to largest. There are different ways to sort the array, here we have mentioned two of them.
Java sort array using the sort() method
In this program, we need to sort the given array in ascending order such that elements will be arranged from smallest to largest. In the given program, we have defined an array of type integer. After that, we used the sort() method of the Arrays class and passed the array to be sorted. We have used the for loop for printing the sorted array.
import java.util.Arrays;
public class SortArrayExample1
{
public static void main(String[] args)
{
//Initializing an array of integer type
int [] arr = new int [] {64, 23, 62, 42, 11, 10, 53, 24};
// Sorting array elements using
Arrays.sort(arr);
System.out.println("Elements of array in ascending order: ");
//prints array using the for loop
for (int i = 0; i < arr.length; i++)
{
System.out.println(arr[i]);
}
}
}
Output of the above code:
Elements of array in ascending order:
10
11
23
24
42
53
62
64
Java sort array using the for loop
We can use the two loops to sort the array in ascending order. The outer loop will select an element, and inner loop allows us to compare the selected element with the rest of the elements.
public class SortArrayElements {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {42, 13, 5, 62, 23, 26, 15};
int temp = 0;
//Sort the array in ascending order
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println();
//Displaying elements of array after sorting
System.out.println("Elements of array in ascending order:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
Output of the above code:
Elements of array in ascending order:
5 13 15 23 26 42 62
Related Articles
Automorphic number in JavaPascal triangle program in Java
Factorial using recursion in java
Java random number between 1 and 10
Palindrome program in Java
Floyd triangle in Java
Pyramid pattern programs in Java
Star pattern programs in Java
Number pattern programs in Java
Java program to find area of rectangle
Matrix multiplication in Java
Electricity bill program in Java
Java program to find area of triangle
Area of circle program in Java
Remove duplicate elements from array in Java
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Convert decimal to hexadecimal in Java
Simple interest program in Java