Python sublist by index

I've been working on implementing common sorting algorithms into Python, and whilst working on selection sort I ran into a problem finding the minimum value of a sublist and swapping it with the first value of the sublist, which from my testing appears to be due to a problem with how I am using min[] in my program.

Here is my code:

def selection_sort[li]: for i in range[0, len[li]]: a, b = i, li.index[min[li[i:]]] li[a], li[b] = li[b], li[a]

This works fine for lists that have zero duplicate elements within them:

>>> selection_sort[[9,8,7,6,5,4,3,2,1]] [1, 2, 3, 4, 5, 6, 7, 8, 9]

However, it completely fails when there are duplicate elements within the list.

>>> selection_sort[[9,8,8,7,6,6,5,5,5,4,2,1,1]] [8, 8, 7, 6, 6, 5, 5, 5, 4, 2, 9, 1, 1]

I tried to solve this problem by examining what min[] is doing on line 3 of my code, and found that min[] returns the index value of the smallest element inside the sublist as intended, but the index is of the element within the larger list rather than of the sublist, which I hope this experimentation helps to illustrate more clearly:

>>> a = [1,2,1,1,2] >>> min[a] 1 # expected >>> a.index[min[a]] 0 # also expected >>> a.index[min[a[1:]]] 0 # should be 1?

I'm not sure what is causing this behaviour; it could be possible to copy li[i:] into a temporary variable b and then do b.index[min[b]], but copying li[i:] into b for each loop might require a lot of memory, and selection sort is an in-place algorithm so I am uncertain as to whether this approach is ideal.

question from://stackoverflow.com/questions/65643799/find-index-of-minimum-value-in-a-python-sublist-min-returns-index-of-minimum

Video liên quan

Chủ Đề