都是一些简单的排序算法,用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即代表数组在排序过程中出现变化的次数