收藏:①极市开发DeepLearning ②Git使用

经典排序的python实现

 具体原理我这里就不解释了,可以查看数据结构课本或者百度百科
这里只给出相应的代码(很简洁)

1
__author__ = "WSX" 2 class sort: 3 def __init__(self,): 4 pass 5 6 def merger(self, left , right): # 合并两个有序列表 7 i = 0; j = 0 ; result = [] 8 while left and right: 9 if left[i] <= right[j]: 10 result.append(left.pop(0)) 11 else: 12 result.append(right.pop(0)) 13 result += left[:] 14 result += right[:] 15 return result 16 17 def mergeSort(self, L): #归并排序 18 if len(L) == 1: 19 return L 20 mid = len(L) // 2 21 left = self.mergeSort(L[:mid]) 22 right = self.mergeSort(L[mid:]) 23 return self.merger(left, right) 24 25 def insert1(self, L): #直接插入排序 俩个for实现 26 for i in range(1,len(L)): 27 temp = L[i] 28 for j in range(i-1,-1,-1): 29 if L[i] < L[j]: 30 L[j+1] = L[j] 31 else: 32 j += 1 33 break 34 L[j] = temp 35 return L 36 37 def insert2(self, L): #直接插入排序 for 结合 while 38 for i in range(1, len(L)): 39 temp = L[i] 40 j = i-1 41 while j >=0 and temp < L[j]: 42 L[j+1] = L[j] 43 j -= 1 44 L[j+1] = temp 45 return L 46 47 def bubblk(self, L): #冒泡排序 48 for i in range(len(L)-1): 49 for j in range(len(L)-i-1): 50 if L[j+1] < L[j]: 51 L[j+1], L[j] = L[j], L[j+1] 52 return L 53 54 def quickSort1(self,L): #快速排序 55 if len(L) <= 1: 56 return L 57 else: 58 return self.quickSort1([i for i in L[1:] if i < L[0]]) + [L[0]] + self.quickSort1([j for j in L[1:] if j > L[0]]) 59 60 def shellSort(self, L): 61 pass 62 63 def selectSort(self, L): #选择排序 64 for i in range(len(L) -1 ): 65 index = i 66 for j in range(i+1, len(L)): 67 if L[j] < L[index]: 68 index = j 69 L[index], L[i] = L[i] ,L[index] 70 return L 71 72 def sortHeap(self,L): #堆排序 73 def heap(L, size, root): 74 larger = root 75 left = 2 * root + 1; 76 right = 2 * root + 2 77 if left < size and L[left] > L[larger]: 78 larger = left 79 if right < size and L[right] > L[larger]: 80 larger = right 81 if larger != root: 82 L[larger], L[root] = L[root], L[larger] 83 heap(L, size, larger) 84 85 def bulidHeap(L): # 初始化堆 86 heapsize = len(L) 87 for i in range(heapsize // 2, -1, -1): 88 heap(L, heapsize, i) 89 90 bulidHeap(L) 91 for i in range(len(L) - 1, -1, -1): 92 L[0], L[i] = L[i], L[0] 93 heap(L, i, 0) 94 return L 95 96 a = sort() 97 print(a.sortHeap([25,3,9,7,55,96]))

 

posted @ 2019-04-21 11:20  WSX_1994  阅读(278)  评论(0编辑  收藏  举报