#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Sorting Algorithms

Insertion Sort for Nearly Sorted Array

Insertion Sort builds the final sorted array one element at a time, by taking each element and inserting it into its correct position among the already-sorted portion. It is particularly efficient when the input array is nearly sorted — meaning most elements are already close to their final position.

Why It Excels on Nearly Sorted Data

Insertion Sort's inner loop only shifts elements while they are out of order. In a nearly sorted array, very few shifts are needed per element, so the algorithm approaches linear time performance rather than its worst-case quadratic time.

def insertion_sort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        while j >= 0 and arr[j] > key:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key
    return arr

print(insertion_sort([2, 1, 4, 3, 5, 6, 8, 7]))

Complexity

CaseTimeSpace
Best (nearly/fully sorted)O(n)O(1)
AverageO(n²)O(1)
Worst (reverse sorted)O(n²)O(1)

Practical Uses

  • Sorting small arrays, or as the final pass in Hybrid sorts like Timsort.
  • Online sorting where elements arrive one at a time and the array stays nearly sorted.
  • Efficient for datasets with only a few out-of-place elements, such as slightly updated sorted logs.

Inversions: The Real Measure of "Nearly Sorted"

An inversion is a pair of positions where the larger value comes first. Insertion sort removes exactly one inversion with every shift, so its running time is O(n + I), where I is the number of inversions. A fully sorted array has zero inversions, while a reversed array has the maximum possible, about n²/2.

Tracing the sample input [2, 1, 4, 3, 5, 6, 8, 7] makes this concrete:

KeyShiftsArray after insertion
11[1, 2, 4, 3, 5, 6, 8, 7]
40unchanged
31[1, 2, 3, 4, 5, 6, 8, 7]
5, 6, 80unchanged
71[1, 2, 3, 4, 5, 6, 7, 8]

Three inversions, three shifts, and only a handful of comparisons beyond one per element. That is why the algorithm feels almost linear on this kind of data.

The k-Sorted Array Variation

A common interview version says every element is at most k positions away from where it belongs. Each element then shifts at most k times, so insertion sort runs in O(n × k). For small k that is excellent. For larger k, a min-heap holding k + 1 elements does better at O(n log k).

import heapq

def sort_k_sorted(arr, k):
    heap = arr[:k + 1]
    heapq.heapify(heap)
    result = []
    for x in arr[k + 1:]:
        result.append(heapq.heappushpop(heap, x))
    while heap:
        result.append(heapq.heappop(heap))
    return result

print(sort_k_sorted([3, 1, 2, 6, 4, 5, 9, 7, 8], 2))

The heap works because the smallest remaining value must be within the next k + 1 elements, so it is always sitting in the heap when we need it.

Measuring how sorted your data is

Before picking an approach, you can count shifts directly. If the count is small relative to n, insertion sort is a good choice.

def count_shifts(arr):
    a = list(arr)
    shifts = 0
    for i in range(1, len(a)):
        key, j = a[i], i - 1
        while j >= 0 and a[j] > key:
            a[j + 1] = a[j]
            j -= 1
            shifts += 1
        a[j + 1] = key
    return shifts

When to Prefer Something Else

  • Random large inputs: merge sort, heap sort or your language's built-in sort will be far faster.
  • Elements far from home: one value at the wrong end, such as the smallest item placed last, forces a long chain of shifts. Nearly sorted means most items are close, not just most items in order.
  • Expensive moves: if each element is large, shifting many times costs more than the comparisons suggest.

Small Details That Matter

  • Use a strict > in the inner loop. Changing it to >= moves equal elements past each other and breaks stability.
  • Binary insertion sort finds the position with binary search, which cuts comparisons, but the number of shifts stays the same.
  • For data that arrives one item at a time, bisect.insort in Python inserts into a sorted list using the same idea.

Takeaway: estimate disorder first. Few inversions favour insertion sort; many favour a general-purpose O(n log n) sort.