Home  >  Article  >  Backend Development  >  Detailed explanation of examples of selection sorting in Python

Detailed explanation of examples of selection sorting in Python

零下一度
零下一度Original
2017-06-25 10:14:291553browse

Selection sort:

Selection sort (Selection sort) is a simple and intuitive sorting algorithm. Here's how it works. First, find the smallest (large) element in the unsorted sequence and store it at the beginning of the sorted sequence. Then, continue to find the smallest (large) element from the remaining unsorted elements, and then put it at the end of the sorted sequence. And so on until all elements are sorted. The main advantage of selection sort relates to data movement. If an element is in the correct final position, it will not be moved. Each time selection sort swaps a pair of elements, at least one of them will be moved to its final position, so sorting a list of n elements requires at most n-1 swaps. Among all sorting methods that rely entirely on exchange to move elements, selection sort is a very good one.

Python implementation:

 1 # selection_sort.py 2 def selection_sort(arr): 3     count = len(arr) 4     for i in range(count-1):    # 交换 n-1 次 5         min = i 6         # 找最小数 7         for j in range(i, count): 8             if arr[min] > arr[j]: 9                 min = j10         arr[min], arr[i] = arr[i], arr[min]    # 交换11     return arr12 13 my_list = [6, 23, 2, 54, 12, 6, 8, 100]14 print(selection_sort(my_list))

The above is the detailed content of Detailed explanation of examples of selection sorting in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn