Java Sort an Array

Arrange array elements in ascending or descending order efficiently

📊 What is Array Sorting?

Array sorting arranges elements in a specific order (ascending or descending). Java provides built-in methods and allows custom sorting algorithms for organizing data efficiently and improving search performance.


// Simple array sorting example
import java.util.Arrays;

public class ArraySort {
    public static void main(String[] args) {
        int[] numbers = {64, 34, 25, 12, 22, 11, 90};
        
        System.out.println("Original array: " + Arrays.toString(numbers));
        
        // Sort using Arrays.sort()
        Arrays.sort(numbers);
        
        System.out.println("Sorted array: " + Arrays.toString(numbers));
    }
}
                                    

Output:

Original array: [64, 34, 25, 12, 22, 11, 90]
Sorted array: [11, 12, 22, 25, 34, 64, 90]

Different Sorting Methods

âš¡

Arrays.sort()

Built-in efficient sorting method

import java.util.Arrays;

int[] arr = {5, 2, 8, 1, 9};
Arrays.sort(arr);
// Result: [1, 2, 5, 8, 9]
🫧

Bubble Sort

Simple comparison-based algorithm

static void bubbleSort(int[] arr) {
    for (int i = 0; i < arr.length - 1; i++) {
        for (int j = 0; j < arr.length - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                // Swap elements
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}
🎯

Selection Sort

Find minimum and place at beginning

static void selectionSort(int[] arr) {
    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;
            }
        }
        // Swap minimum with first element
        int temp = arr[minIndex];
        arr[minIndex] = arr[i];
        arr[i] = temp;
    }
}
📥

Insertion Sort

Insert each element in correct position

static void insertionSort(int[] arr) {
    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;
    }
}

🔹 Complete Array Sorting Program

Here's a comprehensive program demonstrating various sorting techniques:

import java.util.Arrays;
import java.util.Collections;

public class ArraySortComplete {
    public static void main(String[] args) {
        System.out.println("=== Array Sorting Examples ===\n");
        
        // Test array
        int[] original = {64, 34, 25, 12, 22, 11, 90};
        
        // Method 1: Built-in Arrays.sort()
        System.out.println("1. Built-in Arrays.sort():");
        int[] arr1 = original.clone();
        System.out.println("Before: " + Arrays.toString(arr1));
        Arrays.sort(arr1);
        System.out.println("After:  " + Arrays.toString(arr1));
        
        // Method 2: Bubble Sort
        System.out.println("\n2. Bubble Sort:");
        int[] arr2 = original.clone();
        System.out.println("Before: " + Arrays.toString(arr2));
        bubbleSort(arr2);
        System.out.println("After:  " + Arrays.toString(arr2));
        
        // Method 3: Selection Sort
        System.out.println("\n3. Selection Sort:");
        int[] arr3 = original.clone();
        System.out.println("Before: " + Arrays.toString(arr3));
        selectionSort(arr3);
        System.out.println("After:  " + Arrays.toString(arr3));
        
        // Method 4: Insertion Sort
        System.out.println("\n4. Insertion Sort:");
        int[] arr4 = original.clone();
        System.out.println("Before: " + Arrays.toString(arr4));
        insertionSort(arr4);
        System.out.println("After:  " + Arrays.toString(arr4));
        
        // Method 5: Descending order
        System.out.println("\n5. Descending Order:");
        Integer[] arr5 = {64, 34, 25, 12, 22, 11, 90};
        System.out.println("Before: " + Arrays.toString(arr5));
        Arrays.sort(arr5, Collections.reverseOrder());
        System.out.println("After:  " + Arrays.toString(arr5));
        
        // Method 6: String array sorting
        System.out.println("\n6. String Array Sorting:");
        String[] names = {"John", "Alice", "Bob", "Charlie", "Diana"};
        System.out.println("Before: " + Arrays.toString(names));
        Arrays.sort(names);
        System.out.println("After:  " + Arrays.toString(names));
        
        // Performance comparison
        System.out.println("\n7. Performance Test (1000 elements):");
        performanceTest();
    }
    
    // Bubble Sort implementation
    static void bubbleSort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    // Swap arr[j] and arr[j+1]
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
    
    // Selection Sort implementation
    static void selectionSort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            // Swap the found minimum element with the first element
            int temp = arr[minIndex];
            arr[minIndex] = arr[i];
            arr[i] = temp;
        }
    }
    
    // Insertion Sort implementation
    static void insertionSort(int[] arr) {
        int n = arr.length;
        for (int i = 1; i < n; i++) {
            int key = arr[i];
            int j = i - 1;
            
            // Move elements greater than key one position ahead
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j = j - 1;
            }
            arr[j + 1] = key;
        }
    }
    
    // Performance test
    static void performanceTest() {
        int size = 1000;
        int[] testArray = new int[size];
        
        // Fill with random numbers
        for (int i = 0; i < size; i++) {
            testArray[i] = (int)(Math.random() * 1000);
        }
        
        // Test Arrays.sort()
        int[] arr1 = testArray.clone();
        long startTime = System.nanoTime();
        Arrays.sort(arr1);
        long endTime = System.nanoTime();
        System.out.println("Arrays.sort(): " + (endTime - startTime) / 1000000.0 + " ms");
        
        // Test Bubble Sort (smaller array for reasonable time)
        int[] smallArray = Arrays.copyOf(testArray, 100);
        int[] arr2 = smallArray.clone();
        startTime = System.nanoTime();
        bubbleSort(arr2);
        endTime = System.nanoTime();
        System.out.println("Bubble Sort (100 elements): " + (endTime - startTime) / 1000000.0 + " ms");
    }
}

Output:

=== Array Sorting Examples ===

1. Built-in Arrays.sort():
Before: [64, 34, 25, 12, 22, 11, 90]
After: [11, 12, 22, 25, 34, 64, 90]

5. Descending Order:
Before: [64, 34, 25, 12, 22, 11, 90]
After: [90, 64, 34, 25, 22, 12, 11]

6. String Array Sorting:
Before: [John, Alice, Bob, Charlie, Diana]
After: [Alice, Bob, Charlie, Diana, John]

🧠 Test Your Knowledge

Which Java method sorts an array in ascending order?