How does Python insertion sort work?

insertion sort in python using list
insertion sort in python using for loop
insertion sort descending order python
insertion sort python stack overflow
insertion sort in python w3resource
selection sort python
merge sort python
bubble sort: python

Here's a Python implementation of insertion sort, I tried to follow the values on paper but once the counting variable i gets bigger than len(s) I don't know what to do, how/why does it still run?

def sort_numbers(s):
    for i in range(1, len(s)):
        val = s[i]
        j = i - 1
        while (j >= 0) and (s[j] > val):
            s[j+1] = s[j]
            j = j - 1
        s[j+1] = val

def main():
    x = eval(input("Enter numbers to be sorted: "))
    x = list(x)

Or, this one:

def ins_sort(k):
    for i in range(1,len(k)):    #since we want to swap an item with previous one, we start from 1
        j = i                    #bcoz reducing i directly will mess our for loop, so we reduce its copy j instead
        temp = k[j]              #temp will be used for comparison with previous items, and sent to the place it belongs
        while j > 0 and temp < k[j-1]: #j>0 bcoz no point going till k[0] since there is no seat available on its left, for temp
            k[j] = k[j-1] #Move the bigger item 1 step right to make room for temp
            j=j-1 #take k[j] all the way left to the place where it has a smaller/no value to its left.
        k[j] = temp
    return k

Python Program for Insertion Sort, Here's a simple and easy tutorial to learn how to sort using Insertion Sort, and learn about its This article is part 7 of 14 in the series Python Data Structures Tutorial Insertion Sort works best with small number of elements. Insertion Sort algorithm in python. Insertion sort is an in-place sorting algorithm and is efficient algorithm than selection sort and bubble sort. Here a sub-list is maintained which always sorted, as the iterations go on, the sorted sub-list grows until all the elements are sorted.

Consider [3, 2, 1]

The loop starts with 3. Since it is the first item in the list there is nothing else to do.

[3, 2, 1]

The next item is 2. It compares 2 to 3 and since 2 is less than 3 it swaps them, first putting 3 in the second position and then placing 2 in the first position.

[2, 3, 1]

The last item is 1. Since 1 is less than 3 it moves 3 over.

[2, 3, 3]

Since 1 is less than 2 it swaps moves 2 over.

[2, 2, 3]

Then it inserts 1 at the beginning.

[1, 2, 3]

Insertion Sort: A quick tutorial and implementation guide, Or, this one: def ins_sort(k): for i in range(1,len(k)): #since we want to swap an item with previous one, we start from 1 j = i #bcoz reducing i directly will mess our​  Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. Please refer complete article on Insertion Sort for more details! Please write to us at to report any issue with the above content. Writing code in comment? Please use, generate link and share

To see how that implementation works, check it out visualized here:

However, here is a less confusing implementation of insertion sort:

def insertion_sort(seq):
    for i in range(1, len(seq)):
        j = i
        while j > 0 and seq[j - 1] > seq[j]:
            seq[j - 1], seq[j] = seq[j], seq[j - 1]
            j -= 1

How does Python insertion sort work?, How Insertion Sort Works. An array is partitioned into a "sorted" subarray and an "​unsorted" subarray. At the beginning, the sorted subarray contains only the  Insertion Sorting So the insertion sorting algorithm is a well known sorting algorithm that can sort an unsorted array in a worst case time of O(N^2) time. It works by iterating through an array and sorting elements in a linear fashion.

a recursive implementation

def insert(x, L):
    if [] == L:      return [x]
    elif x <= L[0]:  return [x] + L
    else:            return [L[0]] + insert(x,L[1:])

def insertion_sort(L):
    if [] == L:  return []
    else:        return insert(L[0], insertion_sort(L[1:]))

# test
import random

L = [random.randint(1,50) for _ in range(10)]

print L
print insertion_sort(L)

Insertion Sort in Python, The insertion sort, although still O(n2), works in a slightly different way. It always maintains a sorted sublist in the lower positions of the list. Each new item is then​  Insertion sort is similar to arranging the documents of a bunch of students in order of their ascending roll number. Starting from the second element, we compare it with the first element and swap it if it is not in order. Similarly, we take the third element in the next iteration and place it at

If we consider an array from left to right [LeftMost, ..., RightMost], an insertion sort performs the following procedure for each item:

  1. Get the current value i.
  2. Get the value j (where j = i-1 in the first iteration, or basically the first element to the left of i). In the first iteration of the while array[i] and array[j] are to consecutive elements. For example, if array = [... 60, 100, 50, ...], and array[i] is 50, then array[j] is 100.
  3. If the previous value is greater than the current one, then it swaps the two values. Basically if you had something like [..., 60, 100, 50, ...] before this operation takes place, you will end up with [..., 60, 50, 100, ...]. The idea is that you move each item i left as long as there are elements to the left of it that are lower.

    This is the key of the sort algorithm. Once you are done processing at item i, you have a sorted array from where it originally was all the way to the beggining (left most).

  4. Decrease the value of j by one. and go back to step 1 (In this example, this will lead you to compare 50 and 60 and swap them).
If you take a look at the code carefully, you never get a the point where i >= len(s) (range is a function that creates a list, and the value i is not changed inside the loop). You can think of the variable i as an imaginary arrow, pointing to a position in the array that has all sorted elements to its left. The variable j simply moves to the left with i fixed, to swap the original array[i] value until it finds another value that is equal or lower than it.

Sidenote (not important to understand the algorithm, but could be useful): With that in mind, you can deduce that this algorithm's complexity (measured in worst case comparisons) is O(N^2) where N = len(s). It is similar to having two nested for statements.

This video does a great job explaining the above, and you know what they say, an image is worth 1000 words.

6.9. The Insertion Sort, Note: According to Wikipedia "Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less  Insertion sort and its Algorithm. Insertion sort is a sorting algorithm. The process remains the same that put the digit into its right position. Characteristics of Insertion sort. The following are some of the main features of insertion sort.

Python Data Structures and Algorithms: Insertion sort, The diagram given below will make you understand this better. Working of insertion sort. Initial list. 16, 19, 11, 15, 10. First iteration  In Python, the equal to operator does not create another copy of the list. It simply creates another name (alias) for the same list (same on memory). In other words, you just sorted the list 'a' using a different name (i.e. b).

Python: InsertionSort algorithm, Read and learn for free about the following article: Insertion sort If you're seeing this message, it means we're having trouble loading external resources on our website. If you're behind a web filter, please make sure that the domains * and * are unblocked.

Insertion Sort in Python, Boundary Cases: Insertion sort takes maximum time to sort if elements are sorted in reverse order. And it takes minimum time (Order of n) when elements are already sorted. And it takes minimum time (Order of n) when elements are already sorted.

  • You seem to have the exact same code as, is it not working for you or are you curious why it works?
  • It's working for me but I don't understand how it works, because when I follow the values on paper it doesn't get the numbers in order in less than len(s) tries.
  • Does this animation help
  • It helps in that I didn't know how it worked until I watched that GIF, but I still can't follow that Python code, because if you're sorting 3 numbers it seems like the for loop would have to do it in 3 iterations, and from what I can tell it takes more than 3 iterations.
  • x = eval(input(...)) ARGH!!! Don't use eval! It is evil! Really: forget it! It shouldn't be taught to beginners. If you want to parse 1, 2, 3, 4 as a tuple and then convert it into a list use ast.literal_eval: import ast #at the beginning of the file [...] x = list(ast.literal_eval(input("Enter numbers to be sorted:"))).
  • This is in no way an answer to the question.
  • The question is about "OP's code" and it's not asking for code as an answer but an explanation.
  • Hi and welcome to SO. Code should alway be accompanied by an explanation as well.