Java Program to Sort an Array in Ascending Order - The Coding Shala

Home >> Java Programs >> Sort an Array in Ascending Order

 In this post, we will learn how to Sort an Array in Ascending Order in Java.

Java Program to Sort an Array in Ascending Order

You have given an array of integers, return the sorted array in ascending order. 

Example 1:
Input: {2, 1, 3, 4, 6, 4}
Output: {1, 2, 3, 4, 4, 6}

Approach 1

Using Java's sort() Method.

Java Program: 

import java.util.*;

class Solution {
    
    public static void main(String[] args) {
        int[] arr = {4, 5, 3, 1, 0, -1, 55, 34};
        System.out.println("Before sorting array is:");
        for(int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();
        System.out.println("After sorting in acending order array is:");
        
        //using sort method
        Arrays.sort(arr);
        
        for(int num : arr) {
            System.out.print(num + " ");
        }
    }
}

Output: 
Before sorting array is:
4 5 3 1 0 -1 55 34 
After sorting in acending order array is:
-1 0 1 3 4 5 34 55 

Approach 2

Using Loop. (Bubble sort).

Time Complexity: O(n^2).

We can also use different sorting algorithms to sort the array.

Java Program: 

import java.util.*;

class Solution {
    
    public static void main(String[] args) {
        int[] arr = {4, 5, -3, 1, 0, -1, 55, 34};
        System.out.println("Before sorting array is:");
        for(int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();
        System.out.println("After sorting in acending order array is:");
        
        //using loops
        for(int i=0; i<arr.length; i++) {
            for(int j=i+1; j<arr.length; j++) {
                //acending order
                if(arr[j] < arr[i]) {
                    //swap the elements
                    int tmp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = tmp;
                }
            }
        }
        
        for(int num : arr) {
            System.out.print(num + " ");
        }
    }
}

Output: 
Before sorting array is:
4 5 -3 1 0 -1 55 34 
After sorting in acending order array is:
-3 -1 0 1 4 5 34 55 


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

LeetCode - Number of Good Pairs Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala