### 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**- Merge Sort Algorithm
- Quick Sort Algorithm
- Insertion sort algorithm
- Java Program to multiply two numbers
- Java Program to swap two numbers

## Comments

## Post a Comment