Insertion Sort Program in Python
In this piece of code, we will be learning to quote our logic to implement the insertion sort using python.
It is less efficient on large lists than advanced algorithms such as quicksort, heapsort, or merge sort.
- Define a function named
insort(a)that takes in a list
- Inside the function, use a
forloop to iterate through each element in the list, starting from the second element (index 1).
- For each element, store it in a variable
- Use a
whileloop to iterate backwards through the list, starting at the current index and ending at the beginning of the list.
- Inside the
whileloop, compare the element at the current index to the element at the previous index. If the element at the current index is smaller, swap the two elements.
- Decrement the index by 1 at the end of each iteration of the
- After the
forloop completes, the list will be sorted in ascending order.
- Use a
forloop to print each element
def insort(a): for i in range(1, len(a)): b = a[i] j = i - 1 while j >= 0 and b < a[j]: a[j], a[j + 1] = a[j + 1], a[j] j -= 1 a = [5, 6, 4, 1, 3, 2] insort(a) for i in a: print(i)
1 2 3 4 5 6