Python选择排序(1)
Python代码:
""" 选择排序(1)直接选择排序 每次从未排序数组中找出最小的数 如果该数不是第1个数则将其与第1个数交换 例如: 1) 从[3,4,1,2]中找出最小的数1,将数1与第1个数3交换,得到[1,4,3,2] 2) 从[4,3,2]找出最小的数2,将数2与第1个数4交换,得到[2,3,4] """ # 希尔排序 def selectSort(lst): for i in range(len(lst)): pos = i for j in range(i,len(lst)): if lst[j] < lst[pos]: pos = j if pos != i: lst[i],lst[pos] = lst[pos],lst[i] print("选择交换:[%s]:%s [%s]:%s" % (i,lst[i],pos,lst[pos])) if __name__ == "__main__": lst = [3, 6, 9, 1, 4, 7, 2, 8, 5, 0] print("排序前: %s\r\n" %lst) selectSort(lst) print("\r\n排序后: %s" % lst)
输出结果:
E:\python\algorithm>python3 selectSort.py 排序前: [3, 6, 9, 1, 4, 7, 2, 8, 5, 0] 选择交换后:[0]:0 [9]:3 选择交换后:[1]:1 [3]:6 选择交换后:[2]:2 [6]:9 选择交换后:[3]:3 [9]:6 选择交换后:[5]:5 [8]:7 选择交换后:[6]:6 [9]:9 选择交换后:[7]:7 [8]:8 排序后: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
=====结束=====