Skip to main content
added 553 characters in body
Source Link
MrJoe
  • 2.2k
  • 12
  • 30

There is a much simpler method in Python to do an insertion sort using the bisect.insort method

import bisect
array = [1,3,5,7]
bisect.insort_left(array, 2)

>>[1, 2, 3, 5, 7]

With regard to your coding style, I would recommend using the if __name__ == "__main__" guard.

You can also just say for i in range(n) with no need to say (0, n)

You can also use list-comprehension to build the list:

import bisect
def insertion_sort(thelist):
    new_list = []
    for item in thelist:
        bisect.insort_left(new_list, item)
    return new_list


if __name__ == "__main__":
    n = int(input("Enter number of elements: "))
    lst = [input("Please enter a number: ") for i in range(n)]
    new_list = insertion_sort(lst)
    print(*new_list, sep = ", ")

There is a much simpler method in Python to do an insertion sort using the bisect.insort method

import bisect
array = [1,3,5,7]
bisect.insort_left(array, 2)

>>[1, 2, 3, 5, 7]

With regard to your coding style, I would recommend using the if __name__ == "__main__" guard.

You can also just say for i in range(n) with no need to say (0, n)

There is a much simpler method in Python to do an insertion sort using the bisect.insort method

import bisect
array = [1,3,5,7]
bisect.insort_left(array, 2)

>>[1, 2, 3, 5, 7]

With regard to your coding style, I would recommend using the if __name__ == "__main__" guard.

You can also just say for i in range(n) with no need to say (0, n)

You can also use list-comprehension to build the list:

import bisect
def insertion_sort(thelist):
    new_list = []
    for item in thelist:
        bisect.insort_left(new_list, item)
    return new_list


if __name__ == "__main__":
    n = int(input("Enter number of elements: "))
    lst = [input("Please enter a number: ") for i in range(n)]
    new_list = insertion_sort(lst)
    print(*new_list, sep = ", ")
Source Link
MrJoe
  • 2.2k
  • 12
  • 30

There is a much simpler method in Python to do an insertion sort using the bisect.insort method

import bisect
array = [1,3,5,7]
bisect.insort_left(array, 2)

>>[1, 2, 3, 5, 7]

With regard to your coding style, I would recommend using the if __name__ == "__main__" guard.

You can also just say for i in range(n) with no need to say (0, n)