冒泡排序
def bubble_sort(alist):i = 0while i<len(alist):j=0while j<len(alist)-1:if alist[j]>alist[j+1]:alist[j],alist[j+1] = alist[j+1],alist[j]j+=1i+=1l = [2,4,6,8,0,1,3,5,7,9]
bubble_sort(l)
print(l)
选择排序
def select_sort(alist):i = 0while i<len(alist)-1:temp = ij=i+1while j<len(alist):if alist[temp]>alist[j]:temp = jj+=1if not temp == i:alist[i],alist[temp] = alist[temp],alist[i]i += 1
l = [6, 4, 5, 3, 8, 9, 2, 1, 7]
select_sort(l)
print(l)
直接排序
def insert_sort(alist):i=1while i<len(alist):temp = alist[i]j = iwhile j>0 and alist[j - 1] > temp:alist[j] = alist[j-1]j-=1alist[j] = tempi+=1
l = [2,4,6,8,0,1,3,5,7,9]
insert_sort(l)
print(l)
快速排序
def part(alist,l,r):p = alist[l]while l<r:while l<r and alist[r]>p:r-=1alist[l] = alist[r]while l<r and alist[l]<p:l+=1alist[r] = alist[l]alist[l] = preturn ldef quick_sort(alist,l,r):if l<r:p_index = part(alist, l, r)print(alist)quick_sort(alist,l,p_index-1)quick_sort(alist,p_index+1,r)l = [6, 4, 5, 3, 8, 9, 2, 1, 7]
n = len(l)-1
quick_sort(l,0,n)
print(l)
希尔排序
def shell_sort(alist):n = len(alist)gap = n//2while gap>0:for i in range(gap,n):temp = alist[i]j = iwhile alist[j-gap] > temp and j >= gap:alist[j] = alist[j-gap]j -= gapalist[j] = tempgap = gap // 2return arrarr = [6, 4, 5, 3, 8, 9, 2, 1, 7]
print("排序前:", arr)
sorted_arr = shell_sort(arr)
print("排序后:", sorted_arr)