Skip to main content

Public Methods

mergeSort

mergeSort
public static void
The main entry point for sorting an integer array using the merge sort algorithm.
Signature:
public static void mergeSort(int[] arreglo)
Location: MergeSort.java:6-21

Parameters

arreglo
int[]
required
The integer array to be sorted. The array is sorted in-place in ascending order.Valid inputs:
  • Any integer array with length ≥ 0
  • Can contain duplicates
  • Can contain negative numbers
  • null is handled gracefully (method returns immediately)

Return Value

return
void
This method does not return a value. The input array is modified in-place to be sorted in ascending order.

Behavior

The method handles several edge cases automatically:
  • Null array: Returns immediately without error
  • Empty array: Returns immediately (already sorted)
  • Single element: Returns immediately (already sorted)
  • Duplicate elements: Handles correctly with stable sorting
  1. Validates that the array is not null and has more than one element
  2. Creates a temporary array of the same size for merging operations
  3. Calls mergeSortReordenamiento() with initial bounds (0 to length-1)
  4. The original array is sorted in-place upon completion

Example Usage

int[] numbers = {10, 5, 8, 9, 2, 3, 1, 6};
MergeSort.mergeSort(numbers);
// numbers is now: {1, 2, 3, 5, 6, 8, 9, 10}
int[] arr = {64, 34, 25, 12, 22, 11, 90};
MergeSort.mergeSort(arr);
System.out.println(Arrays.toString(arr));
// Output: [11, 12, 22, 25, 34, 64, 90]

Time Complexity

Best Case
O(n log n)
Even if the array is already sorted, merge sort always divides and merges.
Average Case
O(n log n)
The array is divided log n times, and each merge operation is O(n).
Worst Case
O(n log n)
Merge sort has consistent performance regardless of input order.

Space Complexity

Additional Space
O(n)
Requires a temporary array of the same size as the input array for merging.
Call Stack
O(log n)
The recursive calls create a stack depth of log n levels.

Private Methods

The following methods are implementation details and should not be called directly. They are documented here for educational purposes and code understanding.

mergeSortReordenamiento

mergeSortReordenamiento
private static void
Recursive method that implements the divide-and-conquer strategy, splitting the array and coordinating the merge operations.
Signature:
private static void mergeSortReordenamiento(int[] originalArreglo, 
                                           int[] depositoArreglo, 
                                           int indiceInicio,
                                           int indiceFin)
Location: MergeSort.java:23-52

Parameters

originalArreglo
int[]
required
The original array being sorted. This array is modified in-place.
depositoArreglo
int[]
required
A temporary array of the same size used for merging operations. Must have the same length as originalArreglo.
indiceInicio
int
required
The starting index (inclusive) of the subarray to sort. Valid range: 0 to array.length - 1.
indiceFin
int
required
The ending index (inclusive) of the subarray to sort. Valid range: indiceInicio to array.length - 1.

Behavior

Base Case:
if (indiceInicio >= indiceFin) {
    return;  // Subarray has 0 or 1 element, already sorted
}
Recursive Case:
  1. Calculate the midpoint: mitadArreglo = indiceInicio + (indiceFin - indiceInicio) / 2
  2. Recursively sort the left half: indices [indiceInicio, mitadArreglo]
  3. Recursively sort the right half: indices [mitadArreglo + 1, indiceFin]
  4. Merge the two sorted halves using the merge() method
  5. Print the current state of the subarray (educational output)
The midpoint calculation avoids integer overflow by using indiceInicio + (indiceFin - indiceInicio) / 2 instead of (indiceInicio + indiceFin) / 2.
Visual Output: This method prints progress information to the console:
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
...

merge

merge
private static void
Merges two sorted subarrays into a single sorted subarray within the original array.
Signature:
private static void merge(int[] originalArreglo, 
                         int[] depositoArreglo, 
                         int indiceInicio, 
                         int mitadArreglo,
                         int indiceFin)
Location: MergeSort.java:54-103

Parameters

originalArreglo
int[]
required
The original array containing the two sorted subarrays to be merged. Modified in-place.
depositoArreglo
int[]
required
Temporary storage array used during the merge operation. Must have the same length as originalArreglo.
indiceInicio
int
required
The starting index of the first sorted subarray.
mitadArreglo
int
required
The ending index of the first sorted subarray. The second subarray starts at mitadArreglo + 1.
indiceFin
int
required
The ending index of the second sorted subarray.

Behavior

The merge operation works in three phases:
1

Copy to Temporary Array

Copy the entire range [indiceInicio, indiceFin] from originalArreglo to depositoArreglo.
for (int i = indiceInicio; i <= indiceFin; i++) {
    depositoArreglo[i] = originalArreglo[i];
}
2

Merge Sorted Halves

Use three pointers to merge the two sorted halves:
  • contadorPrimerArreglo: Tracks position in left half [indiceInicio, mitadArreglo]
  • contadorSegundoArreglo: Tracks position in right half [mitadArreglo + 1, indiceFin]
  • acompladorArreglos: Tracks where to place the next element in originalArreglo
Compare elements from both halves and place the smaller one in the result.
3

Copy Remaining Elements

After one half is exhausted, copy any remaining elements from the left half. The right half’s remaining elements are already in correct positions.

Three-Pointer Algorithm

int contadorPrimerArreglo = indiceInicio;      // Start of left half
int contadorSegundoArreglo = mitadArreglo + 1; // Start of right half
int acompladorArreglos = indiceInicio;         // Output position
Why no second cleanup loop? If the right half has remaining elements after the main merge loop, they’re already in their correct positions in originalArreglo. Only the left half needs explicit copying.

Example Merge Operation

Before merge:
originalArreglo: [5, 10, 8, 9, ...]
                  ^^^^^ ^^^^^  
                  left  right (both sorted)
After copying to depositoArreglo:
depositoArreglo: [5, 10, 8, 9, ...]
Merge process:
Compare: 5 vs 8  → Choose 5  → [5, ...]
Compare: 10 vs 8 → Choose 8  → [5, 8, ...]
Compare: 10 vs 9 → Choose 9  → [5, 8, 9, ...]
Left remaining: 10           → [5, 8, 9, 10, ...]

Main Method

main

main
public static void
Entry point for testing and demonstrating the merge sort implementation.
Signature:
public static void main(String[] args)
Location: MergeSort.java:105-139

Current Implementation

The main method demonstrates sorting with a predefined array:
int[] originalArreglo = {10, 5, 8, 9, 2, 3, 1, 6};
mergeSort(originalArreglo);
for (int num : originalArreglo) {
    System.out.print(num + " ");
}

Alternative Implementation (Commented Out)

The code includes an alternative implementation using random arrays:
Random numAzar = new Random();
int cantidadElementos = numAzar.nextInt(10) + 1; // 1 to 10 elements
int[] arreglo = new int[cantidadElementos];

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

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

mergeSort(arreglo);

System.out.println("Arreglo ordenado:");
for (int num : arreglo) {
    System.out.print(num + " ");
}
To use the random array version, uncomment lines 117-138 and comment out lines 108-115.

Complete Class Summary

Public Interface

1 public method
  • mergeSort(int[] arreglo)
This is the only method you need to call.

Private Helpers

2 private methods
  • mergeSortReordenamiento(...) - Division
  • merge(...) - Merging
These are implementation details.

Entry Point

1 main method
  • main(String[] args)
For testing and demonstration.

No State

0 instance variablesAll methods are static - no object instantiation needed.

Usage Patterns

// No need to instantiate the class
int[] data = {5, 2, 8, 1, 9};
MergeSort.mergeSort(data);
// data is now sorted
For practical examples and output demonstrations, see the Examples page.

Build docs developers (and LLMs) love