The Selection Sort
2015-11-08 05:59
344 查看
A selection sort looks for the largest value as it makes a pass and, after completing the pass, places it in the proper location.
As with a bubble sort, after the first pass, the largest item is in the correct place.
After the second pass, the next largest is in place. This process continues and requires n−1 passes to sort n items, since the final item must be in place after the (n−1) st pass.
1)循环第一次,先找到最大/最小值,把最小值放在第一位,或者最大的放最后。
2)循环第二次,找到第二小的数字,放在最小值的后面的数字对调
3)以此类推
Q-49: Suppose you have the following list of numbers to sort: [11, 7, 12, 14, 19, 1, 6, 18, 8, 20] which list represents the partially sorted list after three complete passes of selection sort?
[11, 7, 12, 14, 8, 1, 6, 18, 19, 20]
As with a bubble sort, after the first pass, the largest item is in the correct place.
After the second pass, the next largest is in place. This process continues and requires n−1 passes to sort n items, since the final item must be in place after the (n−1) st pass.
def selectionSort(alist): for fillslot in range (len(alist)-1,0,-1): #从后往前循环 #[8,7,6,5,4,3,2,1]#列 positionOfMax=0#最大值的位置为0 for location in range(1,fillslot+1):#行,内部查找 if alist[location]>alist[positionOfMax]: #找到最大值,然后最大值的位置为找到数字的位置 positionOfMax=location #对调 temp = alist[fillslot] alist[fillslot] = alist[positionOfMax] alist[positionOfMax] = temp alist = [54,26,93,17,77,31,44,55,20] selectionSort(alist) print(alist)
1)循环第一次,先找到最大/最小值,把最小值放在第一位,或者最大的放最后。
2)循环第二次,找到第二小的数字,放在最小值的后面的数字对调
3)以此类推
def select_sort(ary): n = len(ary) for i in range(0,n): min = i #最小元素下标标记 for j in range(i+1,n): if ary[j] < ary[min] : min = j #找到最小值的下标 ary[min],ary[i] = ary[i],ary[min] #交换两者 return ary
Q-49: Suppose you have the following list of numbers to sort: [11, 7, 12, 14, 19, 1, 6, 18, 8, 20] which list represents the partially sorted list after three complete passes of selection sort?
[11, 7, 12, 14, 8, 1, 6, 18, 19, 20]
相关文章推荐
- 中兴zxv10 H618B已改64m内存
- 黑苹果不能够断电的处理
- 写在冬日的第一天--一个女程序员第十一年工作总结
- Inorder Successor in BST 解答
- Find Successor & Predecessor in BST
- Spring 整合 Quartz 任务调度框架学习笔记
- PHPmyadmin 和 MySQL 的配置笔记
- Sorting
- freebsd/mac os x timer的实现
- Walls and Gates 解答
- 【LeetCode】Binary Tree Zigzag Level Order Traversal
- [Python爬虫] scrapy爬虫系列 <一>.安装及入门介绍
- Mysql学习篇之---Windows环境下安装
- C++: 拷贝管理
- Integer自动装箱分析
- 匿名内部类构造函数分析
- PHP时间戳、时间戳转北京时间日期
- [并发并行]_[C/C++]_[使用线程本地存储Thread Local Storage(TLS)调用复制文件接口的案例]
- [并发并行]_[C/C++]_[使用线程本地存储Thread Local Storage(TLS)调用复制文件接口的案例]
- 静态内部类和非静态内部类的区别