用Python实现的三种排序算法

都是一些简单的排序算法,用pytho实现主要是想记录自己的学习过程,不多说了,贴代码

冒泡排序:

def bubbleSort(s):

    print s,"\n"
    c = 1;
    for i in range(len(s) - 1):
        for j in range(len(s)  - i - 1):
            if s[j] > s[j + 1]:
                t = s[j]
                s[j] = s[j + 1]
                s[j + 1] = t
                print "the ",c,"th is :",s,"\n"
                c += 1

bubbleSort([3,4,2,5,9,0])

选择排序:

def selectSort(s):
    print s,'\n'  
    c = 1;
    for i in range(len(s) - 1):
        pos = i;
        for j in range(i + 1,len(s)):
            if s[pos] > s[j]:
                pos = j 
                print s[pos],'\n'
                
        temp = s[pos]
        s[pos] = s[i]
        s[i] = temp
            
        print "the ",c,"th is :",s,"\n"
        c += 1

selectSort([3,4,2,5,9,0])

插入排序:

#-*-coding:utf-8-*-
def insertSort(s):
	print s,'\n'
	c = 1
	for i in range(1, len(s)):
		temp = s[i]#保存待插入元素
		pos = i	
		for j in range(i - 1, -1, -1):	
			if temp < s[j]:
				s[j + 1] = s[j]
				pos = j
			s[pos] = temp
			
		print "the ",c,"th is :",s,"\n"
		c += 1
			
insertSort([3,4,2,5,9,0])
每次排序过程对数组产生的变化,都会将数组输出一次,程序中的c即代表数组在排序过程中出现变化的次数


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值