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 158 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 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
• 7,780 points

0 votes
1 answer

## How does % work in Python?

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

0 votes
1 answer

## How does slice notation in Python work?

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

0 votes
0 answers

## How does function definition work in python?

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

0 votes
0 answers

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

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

0 votes
2 answers

## how can i randomly select items from a list?

You can also use the random library's ...READ MORE

+1 vote
2 answers

## how can i count the items in a list?

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

0 votes
0 answers

## how do i use the enumerate function inside a list?

can you give an example using a ...READ MORE

+5 votes
6 answers

## Lowercase in Python

You can simply the built-in function in ...READ MORE

+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

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