Develop a function to implement Insertion Sort

Develop a function to implement Insertion Sort

Python
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

This function takes an array arr as input and returns the sorted array using Insertion Sort algorithm. The basic idea behind Insertion Sort is to divide the array into two parts, sorted and unsorted. Initially, the first element of the array is considered as the sorted part, and the rest of the elements are considered as the unsorted part. Then, for each element in the unsorted part, it is compared with the elements in the sorted part and placed in the correct position. The sorted part of the array is increased by one element for each iteration.

The function starts iterating over the array from index 1, assuming that the first element is already sorted. It then sets the current element as the key variable and starts comparing it with the elements in the sorted part of the array, starting from the last element in the sorted part. If the element in the sorted part is greater than the key, it shifts the element to the right, creating a space for the key. This process continues until it finds the correct position for the key. Finally, the key is placed in its correct position, and the sorted part of the array is increased by one element.

Overall, the time complexity of Insertion Sort is O(n^2) in the worst case, where n is the number of elements in the array. However, it performs better than Bubble Sort and Selection Sort in most cases, especially for small arrays.

Total
1
Shares

Leave a Reply

Previous Post
Network Construction algorithm and working of this algorithm

Network Construction Algorithm: Working, Explanation, and Design Optimization

Next Post
Write A function To implement Linear/Sequential Search.

Write A function To implement Linear/Sequential Search

Related Posts