Arrays.sort() in Java with Examples

Arrays.sort() is a built-in method in Java’s java.util package that provides an efficient and convenient way to sort arrays. This method uses the Dual-Pivot Quicksort algorithm for primitive types and TimSort for objects.

Arrays.sort() Key Points

  1. For Primitive Data Types:
    • Sorts the array in ascending order.
    • Time complexity: O(n log⁡n) on average.
  2. For Objects:
    • Sorts the array in natural order (defined by the compareTo method of the objects).
    • You can use a custom comparator to define the sorting logic.

Arrays.sort() Method Signature

  1. For Primitive Arrays:
    public static void sort(int[] a)
  2. For Object Arrays:
    public static <T> void sort(T[] a)
  3. With Custom Comparator:
    public static <T> void sort(T[] a, Comparator<? super T> c)

Arrays.sort() method Examples in Java

1. Sorting Primitive Arrays

Demonstrates sorting an integer array in ascending order.

package com.javacodepoint.sort;

import java.util.Arrays;

public class ArraySort1 {
	public static void main(String[] args) {
		int[] numbers = { 5, 1, 12, -5, 16 };

		System.out.println("Original Array:");
		System.out.println(Arrays.toString(numbers));

		// Sort the array
		Arrays.sort(numbers);

		System.out.println("Sorted Array:");
		System.out.println(Arrays.toString(numbers));
	}
}

OUTPUT:

2. Sorting Object Arrays (Strings)

It shows how to sort an array of strings alphabetically.

package com.javacodepoint.sort;

import java.util.Arrays;

public class ArraySort2 {
	public static void main(String[] args) {
        String[] names = {"John", "Alice", "Bob", "Diana"};

        System.out.println("Original Array:");
        System.out.println(Arrays.toString(names));

        // Sort the array
        Arrays.sort(names);

        System.out.println("Sorted Array:");
        System.out.println(Arrays.toString(names));
    }
}

OUTPUT:

3. Sorting with a Custom Comparator

Explains sorting an array in reverse order using a custom comparator.

package com.javacodepoint.sort;

import java.util.Arrays;
import java.util.Comparator;

public class ArraySort3 {
	public static void main(String[] args) {
		String[] names = { "John", "Alice", "Bob", "Diana" };

		System.out.println("Original Array:");
		System.out.println(Arrays.toString(names));

		// Sort the array in reverse order
		Arrays.sort(names, Comparator.reverseOrder());

		System.out.println("Sorted Array (Reverse Order):");
		System.out.println(Arrays.toString(names));
	}
}

OUTPUT:

4. Sorting Part of an Array

Illustrates sorting a specific portion of an array using start and end indices.

package com.javacodepoint.sort;

import java.util.Arrays;

public class ArraySort4 {
	public static void main(String[] args) {
		int[] numbers = { 10, 5, 8, 20, 15 };

		System.out.println("Original Array:");
		System.out.println(Arrays.toString(numbers));

		// Sort part of the array (index 1 to 4, exclusive of 4)
		Arrays.sort(numbers, 1, 4);

		System.out.println("Partially Sorted Array:");
		System.out.println(Arrays.toString(numbers));
	}
}

OUTPUT:

5. Sorting Custom Objects

This example demonstrates how to sort an array of custom objects, such as Student objects, based on a specific property (e.g., age). Since custom objects do not have a natural ordering, we use a custom comparator to define the sorting logic.

Sorting Logic: A lambda expression or a comparator is used to specify the criteria for sorting. For example, sorting by age uses: (s1, s2) -> Integer.compare(s1.age, s2.age)

package com.javacodepoint.sort;

import java.util.Arrays;

class Student {
	String name;
	int age;

	public Student(String name, int age) {
		this.name = name;
		this.age = age;
	}

	@Override
	public String toString() {
		return name + " (" + age + ")";
	}
}

public class ArraySort5 {
	public static void main(String[] args) {
		Student[] students = { 
				new Student("Alice", 22), 
				new Student("Bob", 20), 
				new Student("Charlie", 23) 
			};

		System.out.println("Original Array:");
		System.out.println(Arrays.toString(students));

		// Sort by age
		Arrays.sort(students, (s1, s2) -> Integer.compare(s1.age, s2.age));

		System.out.println("Sorted by Age:");
		System.out.println(Arrays.toString(students));
	}
}

OUTPUT:

Java logical programs list


Java Basic Programs

Java String Programs

Java Miscellaneous Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *