排序算法-选择排序

一、选择排序原理:

  选择排序(Selection sort)是一种简单直观的排序算法。第一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,然后再从剩余的未排序元素中寻找到最小(大)元素,然后放到已排序的序列的末尾。以此类推,直到全部待排序的数据元素的个数为零。选择排序是不稳定的排序方法

二、选择排序时间复杂度(n2)

  总的比较次数为:(n-1)+(n-2)+...+2+1 = n(n-1)/2 = ½ n2 - ½n,对于较大的n,我们选择影响较大的项,忽略常数系数。

三、代码实现(源码参照教程数据结构(python语言描述) P49

 1 def selectSort(lyst):
 2     i = 0
 3     while i < len(lyst) - 1:
 4         minindex = i
 5         j = i + 1
 6         while j < len(lyst):
 7             if lyst[j] < lyst[minindex]:
 8                 minindex = j
 9             j += 1
10         if minindex != i:
11             swap(lyst, i, minindex) # 交换数据
12         i += 1
13         print(lyst)
14 
15 
16 def swap(lst, i, j):
17     temp = lst[i]
18     lst[i] = lst[j]
19     lst[j] = temp
20 
21 
22 def getData():
23     return [23, 45, 2, 35, 89, 56, 3]
24 
25 
26 selectSort(getData())

四、排序过程

原文地址:https://www.cnblogs.com/zhuanjiao/p/11657480.html