冒泡排序:
#!/usr/bin/env python # encoding: utf-8 """ @version: ?? @author: phpergao @license: Apache Licence @file: 冒泡排序.py @time: 2016/8/5 10:11 """ def maopao_sort(array): for i in range(len(array)): for j in range(len(array)-1-i,): if array[j]>array[j+1]: tmp=array[j] array[j]=array[j+1] array[j+1]=tmp if __name__ == ‘__main__‘: array=[95,56346,159,1,5,9,3,2,7,0,4,34,21,67,12,] maopao_sort(array) print(array)
执行结果:
选择排序:
#!/usr/bin/env python # encoding: utf-8 """ @version: ?? @author: phpergao @license: Apache Licence @file: 选择排序.py @time: 2016/8/5 12:49 """ def selection_sort(array): for i in range(len(array)): for j in range(i,len(array)): if array[i]>array[j]: tpm=array[i] array[i]=array[j] array[j]=tpm if __name__ == ‘__main__‘: array=[95,56346,159,1,5,9,3,2,7,0,4,34,21,67,12,] selection_sort(array) print(array)
执行结果:
选择排序优化版:
#!/usr/bin/env python # encoding: utf-8 """ @version: ?? @author: phpergao @license: Apache Licence @file: 选择排序优化版.py @time: 2016/8/5 12:54 """ import random def selection_sort(array): for i in range(len(array)): smallest=i for j in range(i,len(array)): if array[smallest]>array[j]: smallest=j tmp=array[i] array[i]=array[smallest] array[smallest]=tmp if __name__ == ‘__main__‘: array=[] for i in range(5000): array.append(random.randrange(100000)) print(array) selection_sort(array) print(array)
执行结果:
原文地址:http://9272317.blog.51cto.com/9262317/1834703