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)1 Answer1
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 the
maxof that slice, O(n) time - you get the
indexof 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:
- the
anparameter (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 using
mininstead ofmaxaccordingly - 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 no
returnis needed and might lead users to expect that the function does not modify the list but create a sorted copy instead - technically,
arris not an array but alist, and you might prefersnake_casetocamelCase(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.
You mustlog in to answer this question.
Explore related questions
See similar questions with these tags.