How does insertion work in Python?

0 votes

I tried implementing insertion sort in python. 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)
    sort_numbers(x)
    print(x)
Oct 8, 2018 in Python by ariaholic
• 7,340 points
28 views

1 answer to this question.

0 votes

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
answered Oct 8, 2018 by charlie_brown
• 7,720 points

Related Questions In Python

0 votes
1 answer

How does % work in Python?

The % (modulo) operator yields the remainder ...READ MORE

answered Oct 10, 2018 in Python by SDeb
• 13,160 points
22 views
0 votes
1 answer

How does slice notation in Python work?

The Python tutorial talks about it (scroll down a ...READ MORE

answered Oct 31, 2018 in Python by Priyaj
• 56,900 points
36 views
0 votes
0 answers

How does function definition work in python?

Is it same as other programming languages ...READ MORE

Jun 13 in Python by Waseem
• 4,480 points
24 views
0 votes
0 answers

How does pillow work in opening and closing images in python?

Is there a separate library that we ...READ MORE

Jul 16 in Python by Waseem
• 4,480 points
25 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 279 views
+4 votes
6 answers
+2 votes
3 answers

How can I play an audio file in the background using Python?

down voteacceptedFor windows: you could use  winsound.SND_ASYNC to play them ...READ MORE

answered Apr 3, 2018 in Python by charlie_brown
• 7,720 points
1,916 views
0 votes
1 answer

How can I compare the content of two files in Python?

Assuming that your file unique.txt just contains ...READ MORE

answered Apr 16, 2018 in Python by charlie_brown
• 7,720 points
125 views