Sort an Array in Ascending Order in Java
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.
Java Program
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
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.
- 1
Arrays.sort(arr)takes the array and sorts its elements in place, in ascending order. - 2For a primitive
int[], this uses a dual-pivot quicksort under the hood — no separate result array is created. - 3After the call,
arritself holds the sorted values, ready to print withArrays.toString().
[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.
Why: Arrays.sort() on a primitive int[] sorts in place using a dual-pivot quicksort, so no separate result array is allocated.
Key Concepts
Approach 2: Java 8
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
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.
- 1
Arrays.stream(arr)converts theint[]into anIntStream. - 2
.sorted()sorts the stream's elements in ascending order, without touching the original array. - 3
.toArray()collects the sorted stream back into a brand-newint[].
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.
Why: sorted() still performs the same comparison sort, but toArray() builds a brand-new array to hold the result instead of sorting in place.