Python Forum
Insertion sort algorithm courtesy of YouTuber Joe James
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Insertion sort algorithm courtesy of YouTuber Joe James
#4
I think that naming can be improved in this example.

IMHO this can be expressed in more pythonic way.

This sort is in-place i.e. it can be applied only to mutable data types (immutables will raise TypeError as they don't support item assignment). Out of built-in mutable data types only list (and bytearray) are accessible by index (sets are unordered and dicts have keys and not indices). So naming parameter as list_ or similar represents much better the sorting ability than A.

Instead of antipattern of range(len()) one can write this instead:

def insertion_sort(list_):
    for i, _ in enumerate(list_):
       for j in reversed(range(i)):
           current, next_ = j, j+1
           if list_[next_] < list_[current]:
               list_[current], list_[next_] = list_[next_], list_[current]
           else:
               break
The only difference is that there will be one wasted cycle at the beginning (i = 0).
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
RE: Insertion sort algorithm courtesy of YouTuber Joe James - by perfringo - Dec-07-2020, 02:11 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Photo a.sort() == b.sort() all the time 3lnyn0 1 1,430 Apr-19-2022, 06:50 PM
Last Post: Gribouillis
  Amortized analysis: Insertion in a list quazirfan 1 1,418 Sep-27-2021, 02:06 AM
Last Post: deanhystad
  insertion sort viku361 1 2,018 Apr-20-2020, 01:47 PM
Last Post: deanhystad
  Detecting USB Device Insertion on Windows 10 Atalanttore 0 2,519 Jan-17-2020, 02:46 PM
Last Post: Atalanttore
  Tree insertion and variable referencing hshivaraj 3 3,464 Dec-10-2017, 04:29 PM
Last Post: Windspar

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020