Sorting Arrays in Java
Sorting is a process of arranging elements in a particular order usually ascending (A–Z / 0–9) or descending (Z–A / 9–0).
In Java, sorting is widely used for searching, reporting, and organizing data efficiently.
What Is Sorting in Java?
Sorting means reordering data elements in a specific order, such as:
- Ascending order: smallest → largest
- Descending order: largest → smallest
- Alphabetical / Lexicographical order: (for Strings)
Sorting makes searching faster and simplifies data processing — e.g., searching student ranks or displaying prices low to high.
Types of Sorting in Java
Java supports two main categories of sorting:

-
Manual Sorting (Algorithm-based)
-
Built-in Sorting (Library-based)
We’ll cover both categories step by step -
1. Algorithm-Based Sorting Techniques
These help beginners understand how sorting logic works internally.

A. Bubble Sort
Repeatedly compare adjacent elements and swap them if they’re in the wrong order.
public class BubbleSortExample {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 4, 2};
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.print("Sorted Array: ");
for (int n : arr) System.out.print(n + " ");
}
}
Output:
Sorted Array: 2 3 4 5 8
Points to Remember:
- Works by “bubbling up” the largest number each round.
- Simple but inefficient for large arrays.
- Time Complexity: O(n²)
B. Selection Sort
Find the smallest element in the unsorted part and move it to the beginning.
public class SelectionSortExample {
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex])
minIndex = j;
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
System.out.print("Sorted Array: ");
for (int n : arr) System.out.print(n + " ");
}
}
Output:
Sorted Array: 11 12 22 25 64
Points to Remember:
- Easy to understand but not efficient for large datasets.
- Time Complexity: O(n²)
C. Insertion Sort
Build the sorted list one element at a time by inserting each element in the correct position.
public class InsertionSortExample {
public static void main(String[] args) {
int[] arr = {9, 5, 1, 4, 3};
for (int i = 1; i < arr.length; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
System.out.print("Sorted Array: ");
for (int n : arr) System.out.print(n + " ");
}
}
Output:
Sorted Array: 1 3 4 5 9
Points to Remember:
- Good for small or nearly sorted arrays.
- Time Complexity: O(n²)
- Best Case: O(n)
D. Merge Sort
Divide the array into halves → sort each half → merge them back together.
public class MergeSortExample {
static void merge(int[] arr, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int[] L = new int[n1];
int[] R = new int[n2];
for (int i = 0; i < n1; i++) L[i] = arr[left + i];
for (int j = 0; j < n2; j++) R[j] = arr[mid + 1 + j];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j])
arr[k++] = L[i++];
else
arr[k++] = R[j++];
}
while (i < n1) arr[k++] = L[i++];
while (j < n2) arr[k++] = R[j++];
}
static void sort(int[] arr, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
sort(arr, left, mid);
sort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
public static void main(String[] args) {
int[] arr = {38, 27, 43, 3, 9, 82, 10};
sort(arr, 0, arr.length - 1);
System.out.print("Sorted Array: ");
for (int n : arr) System.out.print(n + " ");
}
}
Output:
Sorted Array: 3 9 10 27 38 43 82
Points to Remember:
- Uses Divide and Conquer strategy.
- Time Complexity: O(n log n)
- Stable Sort: Yes
- Excellent for large datasets.
E. Quick Sort
Pick a pivot, partition the array, and recursively sort smaller parts.
public class QuickSortExample {
static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
}
static void sort(int[] arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
sort(arr, low, pi - 1);
sort(arr, pi + 1, high);
}
}
public static void main(String[] args) {
int[] arr = {10, 7, 8, 9, 1, 5};
sort(arr, 0, arr.length - 1);
System.out.print("Sorted Array: ");
for (int n : arr) System.out.print(n + " ");
}
}
Output:
Sorted Array: 1 5 7 8 9 10
Points to Remember:
- Fastest average performance: O(n log n)
- Used internally by
Arrays.sort()for primitive types. - Not stable, but in-place.
2. Using Built-in Sorting Methods
Java provides powerful and optimized sorting methods in the java.util.Arrays class.
These methods are preferred for production use because they are fast, reliable, and easy to use.
A) Using Arrays.sort() for Primitive Arrays (Core Java)
This method sorts primitive data types (like int, char, double, etc.) in ascending order by default.
Example:
import java.util.Arrays;
public class BuiltInSortExample {
public static void main(String[] args) {
int[] numbers = {42, 23, 4, 16, 8, 15};
Arrays.sort(numbers); // Ascending order
System.out.println("Ascending Order: " + Arrays.toString(numbers));
}
}
Output:
Ascending Order: [4, 8, 15, 16, 23, 42]
B) Using Arrays.sort() for Object Arrays (Wrapper Classes) (Core Java)
When sorting objects like Integer[], Double[], or Character[], Java uses a different algorithm — TimSort, which is stable and adaptive.
Example:
import java.util.Arrays;
import java.util.Collections;
public class ObjectSortExample {
public static void main(String[] args) {
Integer[] numbers = {42, 23, 4, 16, 8, 15};
Arrays.sort(numbers); // Ascending order
System.out.println("Ascending Order: " + Arrays.toString(numbers));
Arrays.sort(numbers, Collections.reverseOrder()); // Descending order
System.out.println("Descending Order: " + Arrays.toString(numbers));
}
}
Output:
Ascending Order: [4, 8, 15, 16, 23, 42]
Descending Order: [42, 23, 16, 15, 8, 4]
C) Using Arrays.sort() with Strings (Core Java)
Arrays.sort() can also be used to arrange strings in alphabetical (lexicographical) order.
Example:
import java.util.Arrays;
public class StringSortExample {
public static void main(String[] args) {
String[] languages = {"Java", "Python", "C++", "Ruby", "Go"};
Arrays.sort(languages);
System.out.println("Alphabetical Order: " + Arrays.toString(languages));
}
}
Output:
Alphabetical Order: [C++, Go, Java, Python, Ruby]
D) Using Arrays.parallelSort() (Java 8+) (Core / Slightly Advanced)
Introduced in Java 8, this method divides the array into parts and sorts them in parallel threads, improving performance for large datasets.
Example:
import java.util.Arrays;
public class ParallelSortExample {
public static void main(String[] args) {
int[] numbers = {9, 1, 5, 7, 3, 8, 2};
Arrays.parallelSort(numbers);
System.out.println("Parallel Sorted Array: " + Arrays.toString(numbers));
}
}
Output:
Parallel Sorted Array: [1, 2, 3, 5, 7, 8, 9]
E) Using Collections.sort() for Lists (Advanced Java)
This method works with Lists (e.g., ArrayList, LinkedList) instead of arrays.
Example:
import java.util.*;
public class CollectionSortExample {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(5, 3, 9, 1, 7);
Collections.sort(list);
System.out.println("Ascending Order: " + list);
Collections.sort(list, Collections.reverseOrder());
System.out.println("Descending Order: " + list);
}
}
Output:
Ascending Order: [1, 3, 5, 7, 9]
Descending Order: [9, 7, 5, 3, 1]
F) Sorting Custom Objects using Comparator / Comparable (Advanced Java)
You can sort user-defined objects (like Student, Employee) based on any property such as id, name, or salary.
Example:
import java.util.*;
class Student {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
}
public class SortObjectsExample {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student(3, "Aman"));
students.add(new Student(1, "Ravi"));
students.add(new Student(2, "Neha"));
// Sort by ID
students.sort((s1, s2) -> s1.id - s2.id);
System.out.println("Sorted by ID:");
for (Student s : students)
System.out.println(s.id + " " + s.name);
}
}
Output:
Sorted by ID:
1 Ravi
2 Neha
3 Aman
G) Sorting in Descending Order using Collections.reverseOrder() (Core/Advanced)
Collections.reverseOrder() is a built-in comparator that reverses the natural order of sorting.
Example:
import java.util.*;
public class DescendingSortExample {
public static void main(String[] args) {
Integer[] arr = {5, 1, 4, 2, 3};
Arrays.sort(arr, Collections.reverseOrder());
System.out.println("Descending Order: " + Arrays.toString(arr));
}
}
Output:
Descending Order: [5, 4, 3, 2, 1]
Example – Sorting Custom Objects
import java.util.Arrays;
import java.util.Comparator;
class Student {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
}
public class CustomSortExample {
public static void main(String[] args) {
Student[] students = {
new Student(3, "Aman"),
new Student(1, "Ravi"),
new Student(2, "Neha")
};
// Sort by ID
Arrays.sort(students, Comparator.comparingInt(s -> s.id));
for (Student s : students)
System.out.println(s.id + " - " + s.name);
}
}
Output:
1 - Ravi
2 - Neha
3 - Aman
🏆 Top 5 Interview Questions – Sorting Arrays in Java
1. What are the different ways to sort arrays in Java?
Answer: Java provides two main ways to sort arrays:
- Manual Sorting Algorithms: like Bubble Sort, Selection Sort, Insertion Sort, Merge Sort, and Quick Sort.
- Built-in Sorting Methods: such as
Arrays.sort(),Arrays.parallelSort(), andCollections.sort()(for lists).
Tip: Built-in methods are preferred in real-world applications due to efficiency and optimization.
2. What is the difference between Arrays.sort() and Arrays.parallelSort()?
Answer:
| Feature | Arrays.sort() | Arrays.parallelSort() |
|---|---|---|
| Execution | Single-threaded | Multi-threaded (parallel) |
| Performance | Best for small/medium arrays | Faster for large arrays |
| Introduced in | Java 1.2 | Java 8 |
| Order | Stable sort | Stable sort |
3. Which sorting algorithm does Arrays.sort() use internally?
Answer:
- For primitive types (int, double, etc.), Java uses a Dual-Pivot QuickSort algorithm.
- For object arrays (like Integer[], String[]), Java uses TimSort, a hybrid of Merge Sort and Insertion Sort.
4. How can you sort an array in descending order?
Answer: You can sort an array in descending order using the built-in Collections.reverseOrder() method along with Arrays.sort().
Example:
Integer[] arr = {5, 1, 4, 2, 3};
Arrays.sort(arr, Collections.reverseOrder());
System.out.println(Arrays.toString(arr));
Output:
[5, 4, 3, 2, 1]
5. How can you sort a custom object array in Java?
Answer: You can sort custom objects (like Student, Employee) using a Comparator or Comparable interface.
Example:
Arrays.sort(students, Comparator.comparingInt(s -> s.id));
