Skip to main content

Basic Usage

The simplest way to use the MergeSort implementation is to call the mergeSort() method with your integer array.

Example 1: Predefined Array

This is the example currently active in the source code:
MergeSort.java (lines 108-115)
int[] originalArreglo = {10, 5, 8, 9, 2, 3, 1, 6};

mergeSort(originalArreglo);

for (int num : originalArreglo) {
    System.out.print(num + " ");
}
Output:
Proceso de ordenamiento en subarreglo: 0 a 1
5 10 
Proceso de ordenamiento en subarreglo: 2 a 3
8 9 
Proceso de ordenamiento en subarreglo: 0 a 3
5 8 9 10 
Proceso de ordenamiento en subarreglo: 4 a 5
2 3 
Proceso de ordenamiento en subarreglo: 6 a 7
1 6 
Proceso de ordenamiento en subarreglo: 4 a 7
1 2 3 6 
Proceso de ordenamiento en subarreglo: 0 a 7
1 2 3 5 6 8 9 10 
The output shows the progressive merging of subarrays, demonstrating how merge sort combines sorted sections bottom-up.

Random Array Generation

The implementation includes commented code for generating random test arrays.

Example 2: Random Arrays

MergeSort.java (lines 117-138)
Random numAzar = new Random();
int cantidadElementos = numAzar.nextInt(10) + 1; // Generate 1 to 10 elements
int[] arreglo = new int[cantidadElementos];

for (int i = 0; i < cantidadElementos; i++) {
    arreglo[i] = numAzar.nextInt(100) + 1; // Numbers from 1 to 100
}

// Show original array
System.out.println("Arreglo original:");
for (int num : arreglo) {
    System.out.print(num + " ");
}
System.out.println();

// Sort the array
mergeSort(arreglo);

// Show sorted array
System.out.println("Arreglo ordenado:");
for (int num : arreglo) {
    System.out.print(num + " ");
}
Sample Output:
Arreglo original:
67 23 89 12 45 78 34 
Proceso de ordenamiento en subarreglo: 0 a 1
23 67 
Proceso de ordenamiento en subarreglo: 3 a 4
12 45 
Proceso de ordenamiento en subarreglo: 2 a 4
12 45 89 
Proceso de ordenamiento en subarreglo: 0 a 4
12 23 45 67 89 
Proceso de ordenamiento en subarreglo: 5 a 6
34 78 
Proceso de ordenamiento en subarreglo: 0 a 6
12 23 34 45 67 78 89 
Arreglo ordenado:
12 23 34 45 67 78 89 
To use this version, uncomment lines 117-138 and comment out lines 108-115 in MergeSort.java.

Different Input Scenarios

Small Array (5 elements)

int[] arr = {5, 2, 8, 1, 9};
MergeSort.mergeSort(arr);

System.out.println(Arrays.toString(arr));
Output:
Proceso de ordenamiento en subarreglo: 0 a 1
2 5 
Proceso de ordenamiento en subarreglo: 3 a 4
1 9 
Proceso de ordenamiento en subarreglo: 2 a 4
1 8 9 
Proceso de ordenamiento en subarreglo: 0 a 4
1 2 5 8 9 
[1, 2, 5, 8, 9]

Edge Cases

Example 3: Single Element

int[] arr = {42};
MergeSort.mergeSort(arr);
System.out.println(Arrays.toString(arr));
Output:
[42]
No sorting process output appears because the array has only one element, triggering the base case immediately.

Example 4: Empty Array

int[] arr = {};
MergeSort.mergeSort(arr);
System.out.println(Arrays.toString(arr));
Output:
[]

Example 5: Two Elements

int[] arr = {7, 3};
MergeSort.mergeSort(arr);
System.out.println(Arrays.toString(arr));
Output:
Proceso de ordenamiento en subarreglo: 0 a 1
3 7 
[3, 7]

Example 6: Null Array

int[] arr = null;
MergeSort.mergeSort(arr);
System.out.println("No error - null handled gracefully");
Output:
No error - null handled gracefully
While the method handles null arrays gracefully, it’s better practice to check for null before calling sort methods.

Performance Demonstration

Example 7: Large Array

import java.util.Random;
import java.util.Arrays;

public class PerformanceDemo {
    public static void main(String[] args) {
        Random random = new Random();
        int[] sizes = {100, 1000, 10000};
        
        for (int size : sizes) {
            int[] arr = new int[size];
            for (int i = 0; i < size; i++) {
                arr[i] = random.nextInt(10000);
            }
            
            long startTime = System.nanoTime();
            MergeSort.mergeSort(arr);
            long endTime = System.nanoTime();
            
            double duration = (endTime - startTime) / 1_000_000.0;
            System.out.printf("Size: %5d | Time: %.2f ms%n", size, duration);
            
            // Verify it's sorted
            for (int i = 1; i < arr.length; i++) {
                if (arr[i] < arr[i-1]) {
                    System.out.println("Error: Array not sorted!");
                    break;
                }
            }
        }
    }
}
Sample Output:
Size:   100 | Time: 0.85 ms
Size:  1000 | Time: 1.23 ms
Size: 10000 | Time: 3.45 ms
To see this performance test, you’ll need to suppress the progress output by commenting out lines 47-51 in mergeSortReordenamiento().

Comparing with Other Sorting Algorithms

Example 8: Side-by-Side Comparison

import java.util.Arrays;
import java.util.Random;

public class SortingComparison {
    public static void main(String[] args) {
        Random random = new Random();
        int size = 1000;
        
        // Create three identical arrays
        int[] arr1 = new int[size];
        for (int i = 0; i < size; i++) {
            arr1[i] = random.nextInt(10000);
        }
        int[] arr2 = Arrays.copyOf(arr1, arr1.length);
        int[] arr3 = Arrays.copyOf(arr1, arr1.length);
        
        // Test MergeSort
        long start = System.nanoTime();
        MergeSort.mergeSort(arr1);
        long mergeSortTime = System.nanoTime() - start;
        
        // Test Arrays.sort (Dual-Pivot Quicksort)
        start = System.nanoTime();
        Arrays.sort(arr2);
        long javaSortTime = System.nanoTime() - start;
        
        // Test Arrays.sort on pre-sorted (worst case for basic quicksort)
        start = System.nanoTime();
        Arrays.sort(arr3);
        long preSortedTime = System.nanoTime() - start;
        
        System.out.printf("MergeSort time:        %.2f ms%n", mergeSortTime / 1_000_000.0);
        System.out.printf("Java Arrays.sort:      %.2f ms%n", javaSortTime / 1_000_000.0);
        System.out.printf("Arrays.sort (sorted):  %.2f ms%n", preSortedTime / 1_000_000.0);
        
        // Verify all sorted correctly
        System.out.println("\nVerification:");
        System.out.println("arr1 sorted: " + isSorted(arr1));
        System.out.println("arr2 sorted: " + isSorted(arr2));
        System.out.println("Results equal: " + Arrays.equals(arr1, arr2));
    }
    
    private static boolean isSorted(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] < arr[i-1]) return false;
        }
        return true;
    }
}

Integration Examples

Example 9: Using in a Class

public class StudentGradeProcessor {
    private int[] grades;
    
    public StudentGradeProcessor(int[] grades) {
        this.grades = grades;
    }
    
    public void analyzeGrades() {
        // Sort grades using MergeSort
        MergeSort.mergeSort(grades);
        
        // Calculate statistics
        System.out.println("Lowest grade: " + grades[0]);
        System.out.println("Highest grade: " + grades[grades.length - 1]);
        
        double median;
        if (grades.length % 2 == 0) {
            median = (grades[grades.length/2 - 1] + grades[grades.length/2]) / 2.0;
        } else {
            median = grades[grades.length/2];
        }
        System.out.println("Median grade: " + median);
        
        double average = 0;
        for (int grade : grades) {
            average += grade;
        }
        average /= grades.length;
        System.out.println("Average grade: " + average);
    }
    
    public static void main(String[] args) {
        int[] testGrades = {85, 92, 78, 95, 88, 76, 90, 82};
        StudentGradeProcessor processor = new StudentGradeProcessor(testGrades);
        processor.analyzeGrades();
    }
}
Output:
Proceso de ordenamiento en subarreglo: 0 a 1
85 92 
Proceso de ordenamiento en subarreglo: 2 a 3
78 95 
Proceso de ordenamiento en subarreglo: 0 a 3
78 85 92 95 
Proceso de ordenamiento en subarreglo: 4 a 5
76 88 
Proceso de ordenamiento en subarreglo: 6 a 7
82 90 
Proceso de ordenamiento en subarreglo: 4 a 7
76 82 88 90 
Proceso de ordenamiento en subarreglo: 0 a 7
76 78 82 85 88 90 92 95 
Lowest grade: 76
Highest grade: 95
Median grade: 86.5
Average grade: 85.75

Understanding the Output

Interpreting Progress Messages

The implementation prints progress information as it sorts. Here’s how to read it:
Proceso de ordenamiento en subarreglo: 0 a 3
5 8 9 10
This means:
  • “Proceso de ordenamiento en subarreglo”: “Sorting process in subarray”
  • “0 a 3”: Indices 0 through 3 (inclusive)
  • “5 8 9 10”: The sorted contents of that subarray after merging
For the array {10, 5, 8, 9, 2, 3, 1, 6}, the output shows:
  1. Base merges (pairs):
    • Indices 0-1: [5, 10]
    • Indices 2-3: [8, 9]
    • Indices 4-5: [2, 3]
    • Indices 6-7: [1, 6]
  2. Second level (groups of 4):
    • Indices 0-3: [5, 8, 9, 10]
    • Indices 4-7: [1, 2, 3, 6]
  3. Final merge (entire array):
    • Indices 0-7: [1, 2, 3, 5, 6, 8, 9, 10]

Next Steps

Code Structure

Learn about the architecture and how the methods work together

API Reference

Detailed documentation of all methods and parameters

Algorithm Theory

Understand the merge sort algorithm concepts

Complexity Analysis

Deep dive into time and space complexity

Build docs developers (and LLMs) love