码迷,mamicode.com
首页 > 编程语言 > 详细

python 算法

时间:2016-08-05 18:08:15      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:version   file   python   算法   

冒泡排序:

#!/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)

执行结果:

技术分享

python 算法

标签:version   file   python   算法   

原文地址:http://9272317.blog.51cto.com/9262317/1834703

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!