1. 程式人生 > >數據結構學習(冒泡、選擇、插入、快速排.....

數據結構學習(冒泡、選擇、插入、快速排.....

num 插入 int emp range 節點 position __name__ cts

#coding=utf-8 ‘‘‘ 數據結構排序 ‘‘‘ #函數冒泡排序 # 參數alist:被排序的列表 def bubbleSort(alist): for num in range(len(alist)-1,0,-1): for i in range(num): if alist[i] < alist[i+1]: #進行當前位置和下一個位置的交換 alist[i] = alist[i]^alist[i+1] alist[i+1] = alist[i]^alist[i+1] alist[i] = alist[i]^alist[i+1] return alist #函數選擇排序 # 參數alist:被排序的列表 def selectSort(alist): for num in range(len(alist)-1,0,-1): positionMax = 0 for index in range(1,num+1): if alist[positionMax] < alist[index]: positionMax = index # temp = alist[num] # alist[num] = alist[positionMax] # alist[positionMax] =temp alist[num] = alist[num]^alist[positionMax] alist[positionMax] = alist[num]^alist[positionMax] alist[num] = alist[num]^alist[positionMax] print alist[num] return alist #函數插入排序 # 參數alist:被排序的列表 def insertSort(alist): for index in range(1,len(alist)): temp = alist[index] protion = index while alist[protion-1] > temp and protion > 0: alist[protion] = alist[protion-1] protion = protion-1 alist[protion] = temp return alist number=[54,26,93,17,77,31,44,55,21] #快速排序 # 參數alist:被排序的列表 # 參數low:左側起始位置 # 參數hegh:右側終止位置 def quickSort(alist,low,hegh): if low < hegh: pos = findpos(alist,low,hegh) quickSort(alist, low, pos-1) quickSort(alist, pos+1, hegh) return alist #快排中查找中間節點 # 參數alist:被產訊的列表 # 參數low:左側起始位置 # 參數hegh:右側終止位置 def findpos(alist,left,right): temp = alist[left] while left < right: while left < right and alist[right] >= temp: right -= 1 alist[left] = alist[right] while left < right and alist[left] <= temp: left += 1 alist[right] = alist[left] alist[right] = temp return right if __name__ == "__main__": # #測試冒泡排序: # num = bubbleSort(number) # print num # #調用選擇排序 # num = selectSort(number) # print num #調入插入排序 num = insertSort(number) print num # #快速排序 # num = quickSort(number, 0, len(number)-1) # print num

數據結構學習(冒泡、選擇、插入、快速排.....