Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up
Insertion Sort for Nearly Sorted Array

Insertion Sort for Nearly Sorted Array

Beginner 4 min read 23 Sep 2025 1.83K views
Insertion Sort for Nearly Sorted Array

Insertion Sort for Nearly Sorted Array

The Insertion Sort Algorithm is a simple comparison-based sorting algorithm that builds the sorted array one element at a time by inserting each element into its correct position in the sorted portion of the array. It is particularly efficient for nearly sorted arrays, where elements are close to their final positions, requiring fewer comparisons and shifts. This makes it ideal for scenarios where the input is already partially sorted.

DSA skills can boost your tech salary by 25% in 2025. Enroll in our Free DSA Course with Certificate today!

Example:

  • Input: nums = [2, 1, 3, 5, 4, 6] (nearly sorted)
  • Output: [1, 2, 3, 4, 5, 6]
  • Explanation: The array is sorted in ascending order.

Logic

Enter an array of numbers (comma-separated) to sort it using the Insertion Sort algorithm.

Program (Python - Insertion Sort Implementation)

The following Python code implements the Insertion Sort algorithm with O(n²) time complexity in the worst case, but it performs close to O(n) for nearly sorted arrays, where n is the length of the array.


def insertionSort(nums):
    for i in range(1, len(nums)):
        key = nums[i]
        j = i - 1
        # Shift elements that are greater than key to the right
        while j >= 0 and nums[j] > key:
            nums[j + 1] = nums[j]
            j -= 1
        # Place key in its correct position
        nums[j + 1] = key
    return nums

# Example usage
nums = [2, 1, 3, 5, 4, 6]
print(insertionSort(nums))  # Output: [1, 2, 3, 4, 5, 6]

Output

For the input nums = [2, 1, 3, 5, 4, 6], the output is:


[1, 2, 3, 4, 5, 6]

Explanation:

The nearly sorted array is sorted in ascending order using the insertion sort algorithm.

Full-Stack Java Developers earn up to ₹38 LPA in India’s thriving tech market. Launch your high-paying career with our Full Stack Java Developer course today!

Test yourself in 5 minutes

Take the free Datastructures skill challenge to see your strengths and the gaps to fix next.

Start the challenge
Share LinkedIn X Facebook WhatsApp

About the author

Amit Kumar

Amit Kumar

Software Engineer And Author

Experienced Software Engineer with a demonstrated history of working in the professional training & coaching industry. Skilled in Asp.net MVC, Angular, Language Integrated Query (LINQ), SQL, C++, and HTML. Strong engineering professional graduated from Sathyabama University.

Keep learning

Courses that go with this tutorial