3
\$\begingroup\$

I am a rookie and I need help optimizing thisSelectionSort() algorithm which I have tried using Python.

def selectionSort(arr,an):    for lastUnsortedInteger in range(an-1,0,-1):        largest = arr.index(max(arr[0:lastUnsortedInteger+1]))        swap(arr,largest,lastUnsortedInteger)    return arrdef swap(arr,ai,aj):    arr[ai],arr[aj] = arr[aj],arr[ai]if __name__ == '__main__':    an = int(input())    arr = list(map(int,input().strip().split()))    selectionSort(arr,an)    print("Sorted using SelectionSort():\n")    for ai in arr:        print(arr)
Jamal's user avatar
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
askedJul 2, 2020 at 13:07
ashwin2125's user avatar
\$\endgroup\$

1 Answer1

4
\$\begingroup\$

Seems like you already incorporated a few of the suggestions from back when this was on StackOverflow, e.g. changing the inner loop tomax. However, you do so in a very inefficient way:

  • you create a slice of the list, O(n) time and space
  • you get themax of that slice, O(n) time
  • you get theindex of that element, O(n) time

Instead, you can get themax of therange of indices, using akey function for comparing the actual values at those indices:

largest = max(range(0, lastUnsortedInteger+1), key=arr.__getitem__)

This way, this step has only O(n) time (for Python 3).

Some other points:

  • thean parameter (the length of the array/list) is not necessary, you can uselen
  • in my opinion, it is a bit simpler looping from first to last index, and usingmin instead ofmax accordingly
  • since the swap is a single line now and only used once, we could inline this directly into the sorting function
  • the function modifies the list in-place, so noreturn is needed and might lead users to expect that the function does not modify the list but create a sorted copy instead
  • technically,arr is not an array but alist, and you might prefersnake_case tocamelCase (it's "Python" after all)

My version:

def selection_sort(lst):    for i in range(len(lst) - 1):        k = min(range(i, len(lst)), key=lst.__getitem__)        lst[i], lst[k] = lst[k], lst[i]

Needless to say, for all practical purposes you should just usesorted orsort.

answeredJul 2, 2020 at 13:34
tobias_k's user avatar
\$\endgroup\$

You mustlog in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.