Recursive Sorting Algorithms In Data Structure : Merge & Quick Sort in Java

Different Recursive Sort Algorithms

Once you move past the basics of computer science, data structures and algorithms (DSA) come next. One of the first topics you will hit there is recursive sorting algorithms.

They teach you how a big problem can be solved by breaking it into smaller copies of itself. In this guide, we cover the sorting algorithms that use recursion, with Merge Sort in Java as the main example, plus Quick Sort and a recursive Bubble Sort.

This guide is based on where students actually get stuck with recursion in DSA classes and exams. Instead of asking you to memorize code, it shows you how recursive sorting behaves in memory, so the code starts to make sense on its own.

TL;DR: Recursive Sorting Algorithms

AspectSummary
Recursive SortingThe algorithm splits the array into smaller parts and runs the same logic on each part until the pieces are small enough to be sorted already.
Key AlgorithmsMerge Sort and Quick Sort are the two classic recursive sorts. Both use a divide-and-conquer strategy.
Time EfficiencyBoth run in O(n log n) time on average, which is much faster than O(n²) sorts like Bubble Sort on large inputs.
Space OverheadEvery recursive call uses space on the call stack. Merge Sort also needs a temporary array, so it uses O(n) extra space.
Why It MattersRecursive sorting teaches you how to break problems down. That skill carries over to trees, graphs, and most advanced DSA topics.

What Is Recursion?

Recursion is when a function calls itself to solve a smaller version of the same problem. Every recursive function needs two parts:

  • A base case: the simplest input, where the function stops and returns without calling itself again.
  • A recursive case: the function calls itself on a smaller input, moving closer to the base case each time.

Here is about the smallest recursive program you can write in Java:

public class Countdown {

    static void countdown(int n) {
        if (n == 0) {                 // Base case: stop here
            System.out.println("Done!");
            return;
        }
        System.out.println(n);
        countdown(n - 1);             // Recursive call on a smaller problem
    }

    public static void main(String[] args) {
        countdown(3);
    }
}

Output:

3
2
1
Done!

Each call handles one number and hands the rest to the next call. When n reaches 0, the base case stops the chain. If you remove that base case, the calls never end and Java throws a StackOverflowError. Recursive sorting works the same way, just with arrays instead of a single number.

What Is A Recursive Sorting Algorithm?

A sorting algorithm and a recursive function are not the same thing, even though they often work together. A sorting algorithm is a method for putting unsorted items into order. Recursion is a technique where a function calls itself. When a sorting algorithm is built using recursion, we call it a recursive sorting algorithm.

The goal of recursion here is to turn one hard problem (sort this whole array) into many easy ones (sort these tiny pieces). The array keeps getting split until a stopping condition, the base case, is reached. Then the small sorted pieces are combined to form the final sorted array.

The Call Stack: What Is Actually Happening?

This is the part most students skip, and it is exactly the part examiners like to ask about, either in the theory paper or in a lab viva. The call stack is the backbone of every recursive sorting algorithm. If you understand it, the rest gets much easier.

When a function calls itself, the computer does not jump around randomly. It follows a strict rule. The current call is paused, and the new call is placed on top of a stack in memory.

Think of it like a pile of forms. Each recursive call fills out a form and puts it on the pile. The system cannot finish the first form until the last one on top is done.

That is why recursive sorting seems to do nothing at first, then suddenly finishes. In simple terms:

  • The piece of the array gets smaller with each call.
  • No sorted result appears until the deepest call finishes.
  • The final sorted array is built on the way back up, not on the way down.

Once the base case is reached, the calls come off the stack one by one, and each one finishes its work. Seeing this clearly is the difference between students who memorize recursion and students who actually understand it. You will see a printed trace of this later in the debugging section.

Which Sorting Algorithms Are Recursive?

Not every sorting algorithm uses recursion. Here are the five you will meet most often in a DSA course:

  • Merge Sort: recursive by design
  • Quick Sort: recursive by design
  • Bubble Sort: iterative by design, but can be written recursively
  • Selection Sort: iterative by design, but can be written recursively
  • Insertion Sort: iterative by design, but can be written recursively

Merge Sort and Quick Sort are the true recursive sorts. Their whole idea depends on splitting the problem. The other three are loop-based, and professors sometimes ask you to rewrite one of them recursively just to practice recursion. We will do that with Bubble Sort later on.

Why Do Recursive Sorting Algorithms Confuse Students?

We have been helping students with DSA for a long time, and recursive sorting is one of the topics that makes people panic. It is not only because the logic is tricky. There are a few specific reasons.

1) Students Don't See The Problem Getting Smaller

The whole point of recursion is to break a big problem into smaller chunks. Beginners often miss this. To them, the function looks like it keeps calling itself forever. Look at this skeleton of a recursive sort:

void sort(int[] arr, int n) {
    if (n <= 1) return;   // Base case: 0 or 1 item is already sorted
    sort(arr, n - 1);     // Sort a smaller part: the first n-1 items
    // ...then place the last item where it belongs}

Each call works on n - 1 items, so the problem shrinks by one every time. Focus on what one call is supposed to finish, not the whole array. If you can say what part is sorted when a call returns, the shrinking problem becomes obvious.

2) The Base Case Feels Too Simple To Matter

Many students treat the base case like a formality. It is actually the key to correctness, and it is the only thing that stops the recursion.

void mergeSort(int[] arr, int left, int right) {
    if (left >= right) return;   // Stop when one element (or none) is left
    int mid = left + (right - left) / 2;
    // ...recursive calls happen here}

If the base case is missing or wrong, the whole algorithm breaks. Treat the base case as the one result you know is correct, and build your understanding upward from there.

3) Partial Sorting Gets Mistaken For Final Sorting

Most students learn loops first, where you see progress after every step. Recursion does not work that way. If you print the array halfway through a recursive sort, it often looks unsorted, and students think the code is broken.

Stop expecting to see sorting while the recursion goes deeper. The sorted order only shows up during the return phase, when the small sorted parts start combining.

Merge Sort In Java

Merge Sort is the best place to start with recursive sorting. Its logic is clean, it is easy to trace, and it always runs in O(n log n) time. John von Neumann described it back in 1945, and it is still used today.

Merge Sort follows the divide and conquer approach:

  • Divide: split the array into two halves.
  • Conquer: sort each half by calling Merge Sort on it (this is the recursion).
  • Combine: merge the two sorted halves into one sorted array.

Merge Sort is also stable, which means equal items keep their original order. That matters when you sort records, like sorting students by grade while keeping them in name order within each grade.

How Merge Sort Works, Step By Step

Let's sort the array {4, 3, 2, 1} in ascending order.

Merge sort dividing the array 4, 3, 2, 1 into halves and merging them back in sorted order

Step 1: First division. The array is split into two halves: {4, 3} and {2, 1}.

Step 2: Second division. Each half is split again, giving four arrays with one element each: {4}, {3}, {2}, {1}. An array with one element is already sorted, so this is the base case.

Step 3: Merge back up. Now the pieces are merged in pairs. {4} and {3} become {3, 4}. {2} and {1} become {1, 2}. Finally, {3, 4} and {1, 2} are merged into {1, 2, 3, 4}.

Flowchart of the merge sort algorithm showing the divide, sort, and merge steps

How to think about Merge Sort:

  • It is about breaking the problem into small pieces that are already sorted.
  • Each recursive call only sorts its own slice of the array, not the whole thing.
  • The merge step is a calm comparison: look at the front of both sorted halves, take the smaller one, repeat.

Merge Sort Pseudocode

Before the Java code, here is the plan in plain pseudocode:

mergeSort(array, left, right)
    if left >= right:
        return                          // 0 or 1 element, already sorted
    mid = (left + right) / 2
    mergeSort(array, left, mid)         // sort the left half
    mergeSort(array, mid + 1, right)    // sort the right half
    merge(array, left, mid, right)      // combine the two sorted halves

Notice the right half starts at mid + 1, not mid. If you start it at mid, the middle element gets counted twice and the recursion may never end.

Recursive Merge Sort Code In Java

public class MergeSort {

    // Merge two sorted halves: arr[left..mid] and arr[mid+1..right]
    static void merge(int[] arr, int left, int mid, int right) {
        int leftSize = mid - left + 1;
        int rightSize = right - mid;

        // Copy both halves into temporary arrays
        int[] leftPart = new int[leftSize];
        int[] rightPart = new int[rightSize];
        for (int i = 0; i < leftSize; i++) leftPart[i] = arr[left + i];
        for (int j = 0; j < rightSize; j++) rightPart[j] = arr[mid + 1 + j];

        int i = 0, j = 0, k = left;

        // Pick the smaller front element each time
        while (i < leftSize && j < rightSize) {
            if (leftPart[i] <= rightPart[j]) {
                arr[k++] = leftPart[i++];
            } else {
                arr[k++] = rightPart[j++];
            }
        }

        // Copy whatever is left over
        while (i < leftSize) arr[k++] = leftPart[i++];
        while (j < rightSize) arr[k++] = rightPart[j++];
    }

    static void mergeSort(int[] arr, int left, int right) {
        if (left >= right) return;            // Base case: 0 or 1 element

        int mid = left + (right - left) / 2;  // Safe middle index

        mergeSort(arr, left, mid);            // Sort the left half
        mergeSort(arr, mid + 1, right);       // Sort the right half
        merge(arr, left, mid, right);         // Combine the two sorted halves
    }

    public static void main(String[] args) {
        int[] arr = {37, 25, 42, 2, 8, 79, 12};

        System.out.println("Before: " + java.util.Arrays.toString(arr));
        mergeSort(arr, 0, arr.length - 1);
        System.out.println("After:  " + java.util.Arrays.toString(arr));
    }
}

Output:

Before: [37, 25, 42, 2, 8, 79, 12]
After:  [2, 8, 12, 25, 37, 42, 79]

How the program works:

  • main() creates the unsorted array and calls mergeSort() with the first and last index.
  • mergeSort() stops right away if the slice has one element or none. That is the base case.
  • Otherwise, it finds the middle index and calls itself on the left half and then the right half.
  • When both halves come back sorted, merge() copies them into two temporary arrays.
  • It then compares the front items of both arrays, writes the smaller one back into arr, and copies any leftovers at the end.

We calculate the middle as left + (right - left) / 2 instead of (left + right) / 2. Both give the same answer for normal arrays, but the first one cannot overflow when the indexes are very large. It is a good habit, and some professors check for it.

Iterative (Bottom-Up) Merge Sort In Java

Merge Sort does not have to use recursion. The iterative version, also called bottom-up Merge Sort, skips the splitting step. It starts by treating every element as a sorted run of size 1, then merges runs of size 1 into runs of size 2, then 4, then 8, until the whole array is one sorted run.

import java.util.Arrays;

public class MergeSortIterative {

    static void mergeSortIterative(int[] arr) {
        int n = arr.length;
        int[] temp = new int[n];

        // width = size of the sorted runs we merge: 1, 2, 4, 8, ...
        for (int width = 1; width < n; width *= 2) {
            for (int left = 0; left < n; left += 2 * width) {
                int mid = Math.min(left + width - 1, n - 1);
                int right = Math.min(left + 2 * width - 1, n - 1);
                merge(arr, temp, left, mid, right);
            }
        }
    }

    static void merge(int[] arr, int[] temp, int left, int mid, int right) {
        int i = left, j = mid + 1, k = left;

        while (i <= mid && j <= right) {
            temp[k++] = (arr[i] <= arr[j]) ? arr[i++] : arr[j++];
        }
        while (i <= mid) temp[k++] = arr[i++];
        while (j <= right) temp[k++] = arr[j++];

        for (i = left; i <= right; i++) arr[i] = temp[i];
    }

    public static void main(String[] args) {
        int[] arr = {5, 2, 9, 1, 5, 6};
        mergeSortIterative(arr);
        System.out.println("Sorted: " + Arrays.toString(arr));
    }
}

Output:

Sorted: [1, 2, 5, 5, 6, 9]

How the program works:

  • The outer loop controls width, the size of the sorted runs. It doubles each round: 1, 2, 4, and so on.
  • The inner loop walks across the array and picks pairs of neighboring runs.
  • Math.min() keeps mid and right inside the array when the length is not a power of 2.
  • merge() combines each pair using a shared temporary array, then copies the result back.

Recursive vs. Iterative Merge Sort

CriteriaRecursive Merge SortIterative Merge Sort
CodeShorter and closer to the textbook ideaA bit trickier because of the index math
ReadabilityHighMedium
Call stack useO(log n) stack framesNone (just loops)
Extra array spaceO(n)O(n)
Where you see itMost classes, textbooks, and examsWhen you want to avoid recursion entirely

Time And Space Complexity Of Merge Sort

CaseTime Complexity
Best caseO(n log n)
Average caseO(n log n)
Worst caseO(n log n)

Space complexity: O(n), because the merge step needs temporary arrays. The recursion itself only goes about log n calls deep, so the stack adds O(log n) on top of that.

Where Does O(n log n) Come From?

Each time you split, the array is cut in half. You can only halve n items about log n times before every piece has one element. So there are about log n levels of splitting.

At every level, the merge step touches each of the n elements once. So each level costs O(n) work.

Put those together: log n levels times n work per level gives O(n log n). Unlike Quick Sort, the split is always even, so Merge Sort never slows down to O(n²), no matter what the input looks like.

Table comparing merge sort time and space complexity with other sorting algorithms

Advantages And Disadvantages Of Merge Sort

Advantages:

  • It is stable, so equal items keep their original order.
  • It guarantees O(n log n) time, even in the worst case.
  • It works well for external sorting, where the data is too large to fit in memory and lives on disk.
  • The two halves are independent, so the work can be split across multiple threads.

Disadvantages:

  • It needs O(n) extra memory for arrays, which is a problem when memory is tight.
  • For very small arrays, the overhead of recursion and copying makes it slower than simple sorts like Insertion Sort.
  • All the copying into temporary arrays makes it less cache-friendly than Quick Sort, so it is often a bit slower in practice on arrays.

Where Merge Sort Is Used In Real Life

  • Java's own library: Arrays.sort() on objects and Collections.sort() use TimSort, a hybrid of Merge Sort and Insertion Sort. TimSort was designed by Tim Peters for Python. Java sorts primitive arrays like int[] with a dual-pivot Quick Sort instead.
  • External sorting: when a file is too big for memory, it is sorted in chunks that are written to disk and then merged together. That merge step is Merge Sort's idea.
  • Databases: large sorts for things like ORDER BY queries often spill to disk and use the same external merge approach.
  • Linked lists: Merge Sort is the go-to choice for sorting linked lists, as you will see below.

Generic Merge Sort In Java

The version above only sorts int arrays. If you are past the basics, you can write one generic Merge Sort that works on any type that implements Comparable, like String, Integer, or your own classes.

import java.util.Arrays;

public class GenericMergeSort {

    public static <T extends Comparable<? super T>> void sort(T[] arr) {
        T[] temp = arr.clone();
        sort(arr, temp, 0, arr.length - 1);
    }

    private static <T extends Comparable<? super T>> void sort(T[] arr, T[] temp, int left, int right) {
        if (left >= right) return;

        int mid = left + (right - left) / 2;
        sort(arr, temp, left, mid);
        sort(arr, temp, mid + 1, right);
        merge(arr, temp, left, mid, right);
    }

    private static <T extends Comparable<? super T>> void merge(T[] arr, T[] temp, int left, int mid, int right) {
        for (int i = left; i <= right; i++) temp[i] = arr[i];

        int i = left, j = mid + 1, k = left;
        while (i <= mid && j <= right) {
            // "<= 0" keeps equal items in their original order (stable)
            if (temp[i].compareTo(temp[j]) <= 0) arr[k++] = temp[i++];
            else arr[k++] = temp[j++];
        }
        while (i <= mid) arr[k++] = temp[i++];
        while (j <= right) arr[k++] = temp[j++];
    }

    public static void main(String[] args) {
        String[] names = {"Maya", "Alex", "Jordan", "Chris", "Bea"};
        Integer[] scores = {88, 72, 95, 60, 72};

        sort(names);
        sort(scores);

        System.out.println(Arrays.toString(names));
        System.out.println(Arrays.toString(scores));
    }
}

Output:

[Alex, Bea, Chris, Jordan, Maya]
[60, 72, 72, 88, 95]
  • <T extends Comparable<? super T>> means "any type T that knows how to compare itself." That is what lets compareTo() work.
  • The public sort() method makes one temporary array with clone() and reuses it for every merge, instead of creating new arrays on each call.
  • The merge uses <= 0 so equal items keep their original order. That keeps the sort stable.

Merge Sort On A Linked List

Merge Sort is a great fit for linked lists. You cannot jump to the middle of a linked list the way you can with an array, which hurts Quick Sort. But merging two sorted linked lists only needs pointer changes, so there is no need for an extra O(n) array. The only extra space is the O(log n) recursion stack.

public class LinkedListMergeSort {

    static class Node {
        int value;
        Node next;
        Node(int value) { this.value = value; }
    }

    static Node mergeSort(Node head) {
        if (head == null || head.next == null) return head;   // Base case

        // Split the list in half
        Node middle = getMiddle(head);
        Node secondHalf = middle.next;
        middle.next = null;

        Node left = mergeSort(head);
        Node right = mergeSort(secondHalf);
        return merge(left, right);
    }

    // Slow/fast pointers: when fast reaches the end, slow is at the middle
    static Node getMiddle(Node head) {
        Node slow = head, fast = head.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    // Relink nodes in sorted order. No extra array needed.
    static Node merge(Node a, Node b) {
        Node dummy = new Node(0);
        Node tail = dummy;
        while (a != null && b != null) {
            if (a.value <= b.value) { tail.next = a; a = a.next; }
            else { tail.next = b; b = b.next; }
            tail = tail.next;
        }
        tail.next = (a != null) ? a : b;
        return dummy.next;
    }

    public static void main(String[] args) {
        int[] values = {40, 10, 30, 20, 50};
        Node head = null, tail = null;
        for (int v : values) {
            Node node = new Node(v);
            if (head == null) head = node; else tail.next = node;
            tail = node;
        }

        head = mergeSort(head);

        for (Node cur = head; cur != null; cur = cur.next) {
            System.out.print(cur.value + (cur.next != null ? " -> " : "\n"));
        }
    }
}

Output:

10 -> 20 -> 30 -> 40 -> 50
  • The base case returns right away if the list is empty or has one node.
  • getMiddle() uses a slow pointer and a fast pointer. When the fast one reaches the end, the slow one is in the middle.
  • The list is cut in two by setting middle.next = null, and each half is sorted recursively.
  • merge() relinks the nodes in sorted order using a dummy starting node.

How To Debug Merge Sort

When your Merge Sort gives wrong output or crashes, guessing will not help. You need to see what each recursive call is doing. The best trick is to print the slice at the start of each call, indented by how deep the call is:

import java.util.Arrays;

public class MergeSortTrace {

    static void mergeSort(int[] arr, int left, int right, int depth) {
        String indent = "  ".repeat(depth);
        System.out.println(indent + "sort " + Arrays.toString(Arrays.copyOfRange(arr, left, right + 1)));

        if (left >= right) return;

        int mid = left + (right - left) / 2;
        mergeSort(arr, left, mid, depth + 1);
        mergeSort(arr, mid + 1, right, depth + 1);
        merge(arr, left, mid, right);

        System.out.println(indent + "merged " + Arrays.toString(Arrays.copyOfRange(arr, left, right + 1)));
    }

    static void merge(int[] arr, int left, int mid, int right) {
        int[] temp = new int[right - left + 1];
        int i = left, j = mid + 1, k = 0;
        while (i <= mid && j <= right) temp[k++] = (arr[i] <= arr[j]) ? arr[i++] : arr[j++];
        while (i <= mid) temp[k++] = arr[i++];
        while (j <= right) temp[k++] = arr[j++];
        System.arraycopy(temp, 0, arr, left, temp.length);
    }

    public static void main(String[] args) {
        int[] arr = {4, 3, 2, 1};
        mergeSort(arr, 0, arr.length - 1, 0);
    }
}

Output:

sort [4, 3, 2, 1]
  sort [4, 3]
    sort [4]
    sort [3]
  merged [3, 4]
  sort [2, 1]
    sort [2]
    sort [1]
  merged [1, 2]
merged [1, 2, 3, 4]

This trace shows the call stack from earlier in action. The array keeps getting split on the way down, nothing gets sorted until the single-element base cases are reached, and the sorted result is built on the way back up.

A few more debugging tips:

  • Print the left, mid, and right values in each call. Most bugs are off-by-one index mistakes.
  • If you get a StackOverflowError, your base case is wrong or your halves are not getting smaller. Check that the right half starts at mid + 1.
  • Test the merge function on its own with two small sorted arrays before you test the full sort.
  • Test with edge cases: an empty array, one element, all equal values, and an array that is already sorted.

For more on that error, see the StackOverflowError section of our guide to common Java errors.

How To Implement Quick Sort Using Recursion

Quick Sort works differently from Merge Sort. Instead of splitting the array in half, it picks one element called the pivot. Everything smaller than the pivot moves to its left, and everything larger moves to its right. The pivot is now in its final position. Then Quick Sort does the same thing to the left side and the right side.

Let's look at an example. Take the array {3, 4, 1, 2} and choose the last value, 2, as the pivot. The only smaller value is 1, so it goes to the left. The larger values, 3 and 4, go to the right. Now 2 is in the right spot.

Quick sort using recursion, splitting the array around the pivot element

The left side {1} has one element, so it is done. The right side {3, 4} is sorted the same way. Once every side is down to one element, the whole array is {1, 2, 3, 4}.

How to think about Quick Sort:

  • The pivot choice drives everything. A good pivot splits the array into two roughly equal parts.
  • The recursive calls clean up the left side and the right side. The pivot itself never moves again.
  • Each partition places exactly one element, the pivot, in its final spot.

Java code for recursive Quick Sort:

import java.util.Arrays;

public class QuickSort {

    // Put the pivot (last element) in its final spot and return that index
    static int partition(int[] arr, int low, int high) {
        int pivot = arr[high];
        int i = low - 1;              // End of the "smaller than pivot" zone

        for (int j = low; j < high; j++) {
            if (arr[j] < pivot) {
                i++;
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }

        // Move the pivot right after the smaller elements
        int temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;

        return i + 1;
    }

    static void quickSort(int[] arr, int low, int high) {
        if (low < high) {                          // Base case: 0 or 1 element
            int p = partition(arr, low, high);
            quickSort(arr, low, p - 1);            // Sort the left side
            quickSort(arr, p + 1, high);           // Sort the right side
        }
    }

    public static void main(String[] args) {
        int[] arr = {10, 7, 8, 9, 1, 5};
        quickSort(arr, 0, arr.length - 1);
        System.out.println("Sorted: " + Arrays.toString(arr));
    }
}

Output:

Sorted: [1, 5, 7, 8, 9, 10]

How the program works:

  • main() declares the unsorted array and calls quickSort() on the full range.
  • partition() uses the last element as the pivot.
  • It walks through the range and swaps every element smaller than the pivot toward the front. This happens inside the same array, so no new array is created.
  • At the end, the pivot is swapped into the spot right after the smaller elements, and its index is returned.
  • quickSort() then calls itself on the part before the pivot and the part after it. The base case is when a range has one element or none.

One warning: if the array is already sorted and you always pick the last element as the pivot, every partition is lopsided. Quick Sort then slows down to O(n²) time and the recursion goes n calls deep. Picking a random pivot or the median of three values avoids this. For a full walkthrough with more examples, check out our guide to the Quick Sort algorithm.

How To Implement Bubble Sort Using Recursion

In Bubble Sort, you compare two neighboring values at a time. If the left one is bigger, you swap them. After one full pass, the largest value has "bubbled" to the end of the array.

Let's look at an example. Take {20, 10, 40, 30}. First compare 20 and 10. Since 10 is smaller, they swap, giving {10, 20, 40, 30}.

Recursive bubble sort comparing neighboring elements and swapping them

Next compare 20 and 40. They are already in order, so no swap. Then compare 40 and 30. They swap, and the array becomes {10, 20, 30, 40}.

How to think about recursive Bubble Sort:

  • Bubble Sort is naturally a loop-based algorithm. Writing it recursively is a learning exercise, not a speed boost.
  • One recursive call equals one full pass that pushes the largest remaining value to the end.
  • After each pass, the last item is in place, so the next call only needs to handle n - 1 items.

Java code for recursive Bubble Sort:

import java.util.Arrays;

public class BubbleSortRecursive {

    static void bubbleSort(int[] arr, int n) {
        if (n <= 1) return;                 // Base case: nothing left to sort

        // One pass: push the largest of the first n items to position n-1
        for (int i = 0; i < n - 1; i++) {
            if (arr[i] > arr[i + 1]) {
                int temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }

        bubbleSort(arr, n - 1);             // The last item is done. Sort the rest.
    }

    public static void main(String[] args) {
        int[] arr = {9, 1, 2, 3, 11, 4};
        bubbleSort(arr, arr.length);
        System.out.println("Sorted: " + Arrays.toString(arr));
    }
}

Output:

Sorted: [1, 2, 3, 4, 9, 11]

How the program works:

  • main() creates the array and calls bubbleSort() with its full length.
  • The base case stops the recursion once there is one item or none left to sort.
  • A single for loop makes one pass, swapping neighbors that are out of order.
  • The recursive call replaces the outer loop you would see in the normal version. It sorts the first n - 1 items, since the last one is already in place.

If you want the regular loop version with more examples, see our post on Bubble Sort in Java.

Comparison Of Sorting Algorithms

Here is a quick recap of how the recursive sorts compare with each other and with the common loop-based ones.

CriteriaMerge SortQuick SortBubble SortSelection SortHeap Sort
Main ideaDivide and mergePartition around a pivotSwap neighborsSelect the minimumBuild a heap
Usual approachRecursiveRecursiveIterativeIterativeHeap-based
Average timeO(n log n)O(n log n)O(n²)O(n²)O(n log n)
Worst timeO(n log n)O(n²)O(n²)O(n²)O(n log n)
Extra spaceO(n)O(log n) average, O(n) worstO(1) loop versionO(1)O(1)
In-place?NoYesYesYesYes
Stable?YesNoYesNoNo
Best used forStable sorting, linked lists, huge dataFast sorting of arraysLearningLearningGuaranteed speed with low memory

A note on recursive Bubble Sort: it does not use an extra array, but the recursion goes n calls deep, so it uses O(n) stack space. The loop version uses O(1).

Recursion is not only useful for sorting. It is also the natural way to walk through trees. If you want to see that next, read our guide on tree traversal methods.

Can Selection And Insertion Sort Be Recursive?

Yes, but they rarely are. Selection Sort and Insertion Sort were designed around loops, and that is how textbooks, classes, and real code write them. Most developers stick with the loop version because:

  • It is easier to read and does not use extra stack space.
  • It has the same time complexity as the recursive version, without the overhead of function calls.

Still, both can be written recursively, the same way we did with Bubble Sort. The first skeleton in the confusion section above is actually the start of a recursive Insertion Sort. Finishing it is a good practice exercise.

Common Mistakes Students Make With Recursive Sorting

We see the same mistakes again and again in exams and assignments. Most students do not struggle because recursion is hard. They struggle because they rush into code. Watch out for these:

  • Trying to write the whole solution at once. Figure out what one recursive call is responsible for first. The code follows from that.
  • A missing or wrong base case. This causes infinite recursion and a StackOverflowError.
  • Wrong split indexes in Merge Sort. The halves should be left..mid and mid + 1..right. Using mid for both causes duplicates or endless calls.
  • Forgetting the leftover elements when merging. After the main loop, one half usually still has items. If you skip the "copy the rest" loops, those items disappear.
  • Writing into the original array while you still need its old values. That is why the merge step copies the halves into temporary arrays first.
  • Expecting recursion to act like a loop. The output appears on the way back up, not step by step on the way down.
  • Copying code without tracing it. The logic falls apart as soon as the problem changes. Trace at least one small example by hand.
  • Ignoring the call stack. If you do not know what is on the stack, debugging becomes guesswork.

Conclusion

Recursive sorting algorithms are not hard by nature, but they do require a clear picture of how recursion behaves inside memory.

If you are preparing for an exam, here is the most effective way to study: trace one small example on paper, point to the base case, and explain one merge or partition step in your own words. Skip memorizing full code at the start. Once the steps feel obvious, writing the code becomes much easier and you will make fewer mistakes.

This approach will help with more than sorting. Trees, graphs, backtracking, and dynamic programming all lean on the same recursive thinking. If a DSA assignment has you stuck on recursion, our data structures assignment help team can walk you through it.

Takeaways:

  • A recursive function calls itself on a smaller input and stops at a base case.
  • Merge Sort and Quick Sort are recursive by design. Bubble, Selection, and Insertion Sort are loop-based but can be written recursively for practice.
  • Merge Sort splits the array in half, sorts each half, and merges them. It always runs in O(n log n) time and uses O(n) extra space.
  • Quick Sort places one pivot per partition. It averages O(n log n) but can drop to O(n²) with bad pivots.
  • Recursive sorting builds the sorted result on the way back up the call stack.
  • Printing each call with indentation is the fastest way to debug a recursive sort.

Frequently Asked Questions

1. Is Bubble Sort really recursive?

No, Bubble Sort is not recursive by design. It normally uses loops to compare and swap neighbors. You can write it recursively for practice, but it does not make it faster, and it adds stack space.

2. Does recursion always use more memory?

Almost always, yes. Each recursive call needs a frame on the call stack, and the deeper the recursion goes, the more memory it uses. That is why space complexity matters for recursive sorts. Merge Sort only goes about log n calls deep, while a recursive Bubble Sort goes n calls deep.

3. Which recursive sorting algorithm should students learn first?

Start with Merge Sort. Its logic is clear, it is stable, and it is easy to trace step by step. Once you understand how it splits and merges, Quick Sort and other recursive algorithms are much easier to pick up.

4. What is the time complexity of Merge Sort in Java?

Merge Sort runs in O(n log n) time in the best, average, and worst case. The array is split about log n times, and each level of merging touches all n elements. It uses O(n) extra space for the temporary arrays.

5. Is Merge Sort stable?

Yes. As long as the merge step takes from the left half when two values are equal (using <=), equal items keep their original order. That is one reason Java uses a Merge Sort based algorithm, TimSort, to sort objects.

6. Which is faster, Merge Sort or Quick Sort?

On arrays, Quick Sort is usually a little faster in practice because it sorts in place and works well with the CPU cache. Merge Sort is the safer choice when you need a stable sort, a guaranteed O(n log n) worst case, or when you are sorting a linked list.