#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 →
×

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.

Ready to master Data Structures & Algorithms?

Learn DSA hands-on with mentor-led sessions, real interview practice, and placement support.

Explore Course