The selection sort improves on the bubble sort by making only one exchange for every pass through the list. In order to do this, a selection sort looks for the largest value as it makes a pass and, after completing the pass, places it in the proper location.
As with a bubble sort, after the first pass, the largest item is in the correct place. After the second pass, the next largest is in place. This process continues and requires n−1 passes to sort n items, since the final item must be in place after the (n−1) st pass.
Check out the resources below for a review of Selection sort!
def selection_sort(arr): # For every slot in array for fillslot in range(len(arr)-1,0,-1): positionOfMax=0 # For every set of 0 to fillslot+1 for location in range(1,fillslot+1): # Set maximum's location if arr[location]>arr[positionOfMax]: positionOfMax = location temp = arr[fillslot] arr[fillslot] = arr[positionOfMax] arr[positionOfMax] = temp
arr = [3,5,2,7,6,8,12,40,21] selection_sort(arr) arr
[2, 3, 5, 6, 7, 8, 12, 21, 40]
If you like my post please follow me to read my latest post on programming and technology.
You are given two singly linked lists that intersect at some node. Your task is…
A builder plans to construct N houses in a row, where each house can be…
Find the length of the longest absolute path to a file within the abstracted file…
You manage an e-commerce website and need to keep track of the last N order…
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…