python

Insertion Sort in Python

We can create a Python script to sort the array elements using insertion sort. The insertion sort algorithm is only useful for small elements, as it takes more time to sort a large number of elements. Here is how the process works:


Source: Wikipedia.org

 
 

Insertion Sort in Python
# Python script for implementing Insertion Sort
def insertion_sort(arr): 
    # Loop from 1 to arr size
    for i in range(1, len(arr)): 
        k = arr[i] 
        j = i-1
        while j >= 0 and k < arr[j] : 
                arr[j + 1] = arr[j] 
                j -= 1
        arr[j + 1] = k


# Main program to test the above code
arr = [98, 22, 15, 32, 2, 74, 63, 70]
insertion_sort(arr) 
print ("Sorted array:")
for i in range(len(arr)): 
    print ("% d" % arr[i])

Output:

Sorted array:
2
15
22
32
63
70
74
98
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *