用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即代表數組在排序過程中出現變化的次數


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章