Code For Insertion Sort In Java

7 min read

Insertion sort is a simple, intuitive sorting algorithm that builds the final sorted array one element at a time. That's why it is often taught early in computer science courses because its logic mirrors the way people sort playing cards in their hands. Below you will find a detailed explanation of the code for insertion sort in java, complete with a walk‑through of each line, complexity analysis, and practical tips for using it effectively.

How Insertion Sort Works

Insertion sort iterates through the input array, treating the left portion as already sorted and the right portion as unsorted. For each new element, the algorithm shifts larger sorted elements to the right until it finds the correct spot to insert the current element. This process repeats until the whole array is sorted.

Not obvious, but once you see it — you'll see it everywhere That's the part that actually makes a difference..

The algorithm’s simplicity makes it ideal for small datasets or nearly sorted data, where it can achieve linear time performance.

Java Implementation of Insertion Sort

Below is a complete, ready‑to‑run Java class that demonstrates insertion sort on an integer array. The code includes comments that explain each step, making it easy to follow for beginners and useful as a reference for experienced developers Worth keeping that in mind..

public class InsertionSortExample {

    /** 
     * Sorts an array of integers in ascending order using insertion sort.
     * @param arr the array to be sorted; the method sorts it in place
     */
    public static void insertionSort(int[] arr) {
        // Assume the first element (index 0) is already sorted
        for (int i = 1; i < arr.length; i++) {
            int key = arr[i];          // Element to be inserted into the sorted part
            int j = i - 1;             // Index of the last element in the sorted part

            // Move elements of arr[0..i-1] that are greater than key
            // one position to the right to make space for key
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];   // Shift element to the right
                j--;                   // Move to the next element on the left
            }
            // Place the key after the element just smaller than it
            arr[j + 1] = key;
        }
    }

Quick note before moving on.

    /** Utility method to print an array */
    private static void printArray(int[] arr) {
        for (int value : arr) {
            System.Now, out. print(value + " ");
        }
        System.out.

    public static void main(String[] args) {
        int[] data = {9, 4, 6, 2, 7, 5, 3, 8, 1};
        System.out.println("Original array:");
        printArray(data);

        insertionSort(data);

        System.out.println("Sorted array:");
        printArray(data);
    }
}

Walk‑Through of the Code

  1. Method signature – public static void insertionSort(int[] arr) receives an integer array and sorts it in place, meaning no additional array is allocated for the result.
  2. Outer loop – Starts at index 1 because a single‑element subarray (index 0) is trivially sorted. The loop variable i marks the boundary between the sorted and unsorted sections.
  3. Key selection – int key = arr[i]; stores the current element that needs to be positioned correctly.
  4. Inner while loop – Shifts every element larger than key one slot to the right. The condition j >= 0 && arr[j] > key ensures we stop when we either reach the start of the array or find an element ≤ key.
  5. Insertion – After the loop, j points to the element just smaller than key (or -1 if all elements were larger). arr[j + 1] = key; places the key in its correct location.
  6. Printing helper – printArray provides a quick way to visualize the array before and after sorting.
  7. Main method – Demonstrates the algorithm with a sample unsorted array and prints the results.

Step‑by‑Step Example

Consider the array [9, 4, 6, 2, 7]. The algorithm proceeds as follows:

Iteration (i) Key Sorted portion before insertion Actions (shifts) Array after insertion
1 4 [9] 9 → right [4, 9, 6, 2, 7]
2 6 [4, 9] 9 → right [4, 6, 9, 2, 7]
3 2 [4, 6, 9] 9,6,4 → right [2, 4, 6, 9, 7]
4 7 [2, 4, 6, 9] 9 → right [2, 4, 6, 7, 9]

After the final iteration the array is fully sorted And that's really what it comes down to..

Time and Space Complexity

Metric Value
Best case O(n) – occurs when the input is already sorted; the inner while loop never executes.
Average case O(n²) – each element may need to be compared with roughly half of the sorted portion.
Worst case O(n²) – occurs with a reverse‑sorted array; each insertion shifts all previously sorted elements.
Space O(1) – only a few extra variables (key, i, j) are used; sorting is in place.

The official docs gloss over this. That's a mistake.

Because of its quadratic worst‑case time, insertion sort is not suitable for large, random datasets. g.On the flip side, its adaptive nature (performing better on nearly sorted data) and low overhead make it a practical choice for small arrays or as a subroutine in more complex algorithms (e., the final pass of Shell sort or the optimization step in quicksort for sub‑arrays of size ≤ 10).

Short version: it depends. Long version — keep reading The details matter here..

Advantages and Disadvantages

Advantages

  • Simple to understand and implement – ideal for teaching.
  • In‑place sorting with minimal memory usage.
  • Stable: equal elements retain their original relative order.
  • Adaptive: runs in O(n) time when the array is already or nearly sorted.
  • Low constant factors; faster than O(n²) algorithms like selection sort or bubble sort for tiny n.

Disadvantages

  • Inefficient for large, unsorted collections due to O(n²) worst‑case time.
  • Not suitable when strict performance guarantees are required for big data.
  • Still outperformed by O(n log n) algorithms (merge sort, quicksort, heapsort) for n > ~50‑100 in most practical scenarios.

When to Use Insertion Sort in Java

  • Small arrays (typically fewer than 20

Below are additional guidelines that help decide whether insertion sort belongs in your codebase Surprisingly effective..

Practical Scenarios for Insertion Sort in Java

  • Tiny collections – For n ≤ 15–20 the linearithmic cost of divide‑and‑conquer methods becomes noticeable; insertion sort’s linear behavior makes it the fastest option for such small slices.
  • Nearly ordered streams – If incoming data arrives almost sorted (e.g., user inputs that are gradually refined), the algorithm will often run in near‑O(n) time because the inner “while” loop rarely advances far.
  • Memory‑constrained environments – Because the routine works entirely within the supplied array, it incurs no auxiliary heap allocation, which is valuable on embedded platforms or when the call stack is limited.
  • Hybrid subroutines – Many high‑performance libraries embed insertion sort as the final pass of larger sorts (such as Shell sort). The simple shifting logic fits neatly into those pipelines without adding extra bookkeeping.
  • Stability requirement – When you cannot afford an unstable comparison (for instance, sorting records by multiple keys while preserving original order), insertion sort naturally preserves equality ties, making it a safe fallback.

Minimal Implementations

public static void insertionSort(int[] a) {
    for (int i = 1; i < a.length; i++) {
        int key = a[i];
        int j = i - 1;
        // Shift elements that are greater than key one position ahead
        while (j >= 0 && a[j + 1] > key) {
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = key;
    }
}

A lightweight variant adds an early‑exit flag:

boolean swapped = true;
do {
    swapped = false;
    for (int i = 1; i < a.length; i++) {
        if (a[i] < a[i - 1]) {
            int tmp = a[i];
            int j = i - 1;
            while (j >= 0 && a[j + 1] > tmp) {
                a[j + 1] = a[j];
                j--;
            }
            a[j + 1] = tmp;
            swapped = true;
        }
    }
} while (swapped);

The second version stops as soon as a completely sorted prefix is detected, giving an O(n) best‑case bound even for partially reversed inputs.


Conclusion

Insertion sort offers a compelling mix of simplicity, stability, and adaptability. Its quadratic worst‑case runtime is mitigated by its excellent average and best‑case performance on almost‑sorted data, and its in‑place nature eliminates external memory overhead. Think about it: while it cannot replace O(n log n) algorithms for large, randomly distributed datasets, it shines in contexts where low latency matters, where memory is at a premium, or where the data is expected to be close to order. That's why by leveraging its core mechanics—shifting elements until the correct position for the current key—and augmenting them with early‑exit optimizations, developers can integrate insertion sort as a fast, reliable building block within broader sorting strategies or standalone utilities. Choose it wisely, and it will reliably deliver quick, correct results across many real‑world scenarios.

Out This Week

Recently Completed

Try These Next

Continue Reading

Thank you for reading about Code For Insertion Sort In Java. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home