Python implements selection sorting

  • 2020-06-03 06:57:35
  • OfStack

Selection sort:

Selection sorting (Selection sort) is a simple and intuitive sorting algorithm. Here's how it works. First, the smallest (large) element is found in the unsorted sequence and stored at the beginning of the sorted sequence. Then, the smallest (large) element is found from the remaining unsorted elements and placed at the end of the sorted sequence. And so on until all the elements are sorted. The main advantage of selective sorting relates to data movement. If an element is in the correct final position, it will not be moved. The selection sort swaps 1 pair of elements each time, and at least 1 of them will be moved to its final position, so there is a total of up to ES6en-1 swaps for sorting the table of n elements. Of all the sorting methods that rely entirely on swapping to move elements, selective sorting is a very good one.

Python implementation:


 # selection_sort.py
 def selection_sort(arr):
   count = len(arr)
   for i in range(count-1):  #  exchange  n-1  time 
     min = i
     #  To find the minimum number of 
     for j in range(i, count):
       if arr[min] > arr[j]:
         min = j
     arr[min], arr[i] = arr[i], arr[min]  #  exchange 
   return arr
 
 my_list = [6, 23, 2, 54, 12, 6, 8, 100]
 print(selection_sort(my_list))


Related articles: