The selection method can also be regarded as an entry-level sorting algorithm. Compared with the bubble method, its method is more clever. Its starting point is to "pick". Each time, the best value of the array is selected, and Replace the preceding elements, then continue to select the highest value of the remaining elements and repeat the operation. Personally, I think the significance of selection sorting is not the sorting itself, but the method of selection and replacement, which is very helpful for some problems.
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:
# selection_sort.py def selection_sort(arr): count = len(arr) for i in range(count-1): # 交换 n-1 次 min = i # 找最小数 for j in range(i, count): if arr[min] > arr[j]: min = j arr[min], arr[i] = arr[i], arr[min] # 交换 return arr my_list = [6, 23, 2, 54, 12, 6, 8, 100] print(selection_sort(my_list))
The above is the detailed content of Share an example tutorial on implementing selection sorting in Python. For more information, please follow other related articles on the PHP Chinese website!