defbubbleSort(arr):#冒泡排序 l = len(arr) for i in range(l): for j in range(l - i): if j + 1 < l - i and arr[j] > arr[j + 1]: tmp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = tmp return arr
defselectionSort(arr):# 选择排序 l = len(arr) index = 0 for i in range(l): value = arr[i] for j in range(i+1,l): if value < arr[j]: value = arr[j] index = j arr[index] = arr[i] arr[i] = value return arr
插入排序
原理
它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
自己写的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
defchange(arr,i,j): tmp = arr[j] for k in range(i,j)[::-1]: print(k) arr[j] = arr[k] arr[i] = tmp definsertSort(arr):# 插入排序 min_index =0 l = len(arr) for i in range(l): for j in range(i): if arr[j] <= arr[i] and arr[i] < arr[j + 1] and j + 1 < l: print(j) change(arr,i,j) return arr
网上流传的代码
1 2 3 4 5
definsert_Sort(arr): for x in range(1,len(arr)): for i in range(x-1,-1,-1): if(arr[i] > arr[i + 1]): arr[i],arr[i+1] = arr[i+1],arr[i]
defLEFT(i): return2 * i + 1 defRIGHT(i): return2 * i + 2 defadjustHeap(arr,length,i): largest = i while(True): left,right = LEFT(i),RIGHT(i) if(left < length) and (arr[left] > arr[i]): largest = left else: largest = i if(right < length) and (arr[right] > arr[largest]): largest = right if(largest != i): arr[i],arr[largest] = arr[largest],arr[i] i = largest continue else: break defbuildHeap(arr): length = len(arr) for x in range((int)((length - 1)/2),-1,-1): adjustHeap(arr,length,x)
defheapSort(arr): buildHeap(arr) i = len(arr) while(i > 0): arr[0],arr[i-1] = arr[i-1],arr[0] i -= 1 adjustHeap(arr,i,0)