Java ProgramsArraysSort an Array in Ascending Order

Sort an Array in Ascending Order in Java

beginner·  Arrays  ·  Sorting

Problem

Sorting an array in ascending order means rearranging its elements from smallest to largest.

Given an array of integers, sort it in ascending order.

Input
[8, 3, 10, 1, 6]
Output
[1, 3, 6, 8, 10]

Java Program

Java
import java.util.Arrays; public class SortAscending { public static void main(String[] args) { int[] arr = {8, 3, 10, 1, 6}; Arrays.sort(arr); // sorts the array in place, in ascending order System.out.println(Arrays.toString(arr)); } }

Output

[1, 3, 6, 8, 10]

Core Logic

In real code, there's no reason to write a sorting algorithm by hand — Arrays.sort() already sorts an int[] in place in one call.

How It Works
  1. 1Arrays.sort(arr) takes the array and sorts its elements in place, in ascending order.
  2. 2For a primitive int[], this uses a dual-pivot quicksort under the hood — no separate result array is created.
  3. 3After the call, arr itself holds the sorted values, ready to print with Arrays.toString().
For [8, 3, 10, 1, 6], Arrays.sort(arr) rearranges the array in place into [1, 3, 6, 8, 10].
💡

Key Point: This is what you'd actually use in real code — Bubble Sort, Selection Sort, and Insertion Sort are worth learning to understand how sorting works, but Arrays.sort() is faster and battle-tested for everyday use.

Complexity
Time Complexity: O(n log n)Space Complexity: O(1)

Why: Arrays.sort() on a primitive int[] sorts in place using a dual-pivot quicksort, so no separate result array is allocated.

Key Concepts

Arrays.sort()in-place sorting

Approach 2: Java 8

Java
import java.util.Arrays; public class SortAscendingStream { public static void main(String[] args) { int[] arr = {8, 3, 10, 1, 6}; // sorted() leaves the original array untouched, returning a new sorted one int[] result = Arrays.stream(arr).sorted().toArray(); System.out.println(Arrays.toString(result)); } }

Output

[1, 3, 6, 8, 10]

Core Logic

The same sort can be expressed as a stream pipeline instead of an in-place mutation — useful when the original array needs to stay untouched.

How It Works
  1. 1Arrays.stream(arr) converts the int[] into an IntStream.
  2. 2.sorted() sorts the stream's elements in ascending order, without touching the original array.
  3. 3.toArray() collects the sorted stream back into a brand-new int[].
Arrays.stream({8, 3, 10, 1, 6}).sorted().toArray() produces a new array holding [1, 3, 6, 8, 10], leaving the original array unchanged.
💡

Key Point: Unlike Arrays.sort(), which mutates the array in place, this returns a brand-new sorted array — the original stays exactly as it was.

Complexity
Time Complexity: O(n log n)Space Complexity: O(n)

Why: sorted() still performs the same comparison sort, but toArray() builds a brand-new array to hold the result instead of sorting in place.

Key Concepts

StreamIntStreamsorted()

Related Programs