选择排序无疑是最简单直观的排序。它的工作原理如下。
这两个图中都是选择小的数字放前面。
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 26 16:55:14 2016
选择排序:
从第一个元素开始,每一个元素都跟后面所有的元素比较,选择最小的放在前面
比如:
2 3 1 6 5
选择2 和后面的[3 1 6 5]比较
只有1比2小,1和2位置互换
1 3 2 6 5
然后再从[3 2 6 5]中选择第一个元素,和后面每一个元素比较,把最小的放在前面
@author: zang
"""
from matplotlib import pyplot as plt
import random
def selectionSort1(unsortedList):
if len(unsortedList) < 2:
return unsortedList
firstNum = unsortedList.pop(0)
len_list = len(unsortedList)
for i in range(len_list):
if unsortedList[i] < firstNum:
unsortedList[i], firstNum = firstNum, unsortedList[i]
return [firstNum] + selectionSort1(unsortedList)# 递归
def selectionSort(unsortedList):
list_length=len(unsortedList)
for i in range(0,list_length-1):
for j in range(i+1,list_length):
if unsortedList[i] > unsortedList[j]:
unsortedList[i],unsortedList[j] = unsortedList[j],unsortedList[i]
return unsortedList
def plotScatter(inputList):
plt.scatter(range(len(inputList)),inputList)
plt.show()
if __name__ == "__main__":
num_list = range(1000)
unsortedList = random.sample(num_list, 30)
print "unsortedList:"
plotScatter(unsortedList)
print unsortedList
sortedList = selectionSort1(unsortedList)
print "sortedList:"
plotScatter(sortedList)
print sortedList
输入
[338, 487, 633, 511, 957, 636, 236, 384, 425, 166, 626, 828, 34, 870, 183, 377, 490, 717, 850, 437, 207, 942, 921, 523, 316, 37, 209, 122, 28, 124]
输出
[28, 34, 37, 122, 124, 166, 183, 207, 209, 236, 316, 338, 377, 384, 425, 437, 487, 490, 511, 523, 626, 633, 636, 717, 828, 850, 870, 921, 942, 957]
情况 | 性能 |
---|---|
Worst case performance: | O(n2) |
Best case performance: | O(n2) |
Average case performance: | O(n2) |
Worst case space complexity: | O(1) |