-2

I'm trying to create an insertion sort program in python with no built in functions. The only problem is that my program will only sort the first item in a list. What am I doing wrong?

My sort

       def insertionsort(list1):
         for index in range(len(list1)):
           value = list1[index]
           position = index
           while position > 0 and list1[position-1] > value:
              list1[position]=list1[position-1]
              position = position-1
           list1[position] = value
           return(list1)

Example Output

List = [3,1,5,2]

Output = [1,3,5,2]

3 Answers3

1

Fix your indentation like: (The return should be outside the loop)

def insertionsort(list1):
  for index in range(len(list1)):
    value = list1[index]
    position = index
    while position > 0 and list1[position-1] > value:
      list1[position]=list1[position-1]
      position = position-1
    list1[position] = value
  return(list1)


aList = [3, 1, 5, 2]

aList = insertionsort (aList)
print (aList)

And indeed, you can find this anywhere:

https://interactivepython.org/runestone/static/pythonds/SortSearch/TheInsertionSort.html

user2390182
  • 72,016
  • 6
  • 67
  • 89
Jacques de Hooge
  • 6,750
  • 2
  • 28
  • 45
1

Firstly in insertion sort we assume that our first element is sorted. Hence we start iterating in the list from the first element. Secondly, You are using range function over here. range(4) will include numbers starting from 0-3 and will exclude 4. So the correction your code requires is that you need to use range function in below manner: for index in range(1,len(list1)) instead of for index in range(len(list1)) And correct the indent of your return statement.Return statement should be present only when the for loop has done its task as the function code execution will stop once a return is encountered. The sort function sums up as below.

def insertionsort(list1):
     for index in range(1,len(list1)):
       value = list1[index]
       position = index
       while position > 0 and list1[position-1] > value:
          list1[position]=list1[position-1]
          position = position-1
       list1[position] = value
     return(list1)

Another suggestion is to try a dry run of your code before asking for help.It avoids small problems that you can solve on your own and create a better concept for yourself.

Cheers..!!

Pranav Gupta
  • 741
  • 9
  • 10
0

Try out this piece of code :

def insertionSort(alist):
  for index in range(1,len(alist)):

    currentvalue = alist[index]
    position = index

    while position>0 and alist[position-1]>currentvalue:
        alist[position]=alist[position-1]
        position = position-1

    alist[position]=currentvalue


alist = [3,1,5,2]
insertionSort(alist)
print(alist)

I hope it helps.

Kedar Kodgire
  • 482
  • 6
  • 22