1.冒泡排序
1.1冒泡排序
def bubble_sort(li): for i in range(len(li)-1): for j in range(len(li)-i-1): if li[j] > li[j+1]: li[j],li[j+1] = li[j+1],li[j] li=[2,4,5,45,6,74,3] bubble_sort(li) print(li)
1.2冒泡排序改进:
def bubble_sort(li): for i in range(len(li)-1): exchange=False for j in range(len(li)-i-1): if li[j] > li[j+1]: li[j],li[j+1] = li[j+1],li[j] exchange = True if not exchange: return li=[2,4,5,45,6,74,3] bubble_sort(li) print(li)
2.选择排序
2.1新建列表选择排序:
new_list=[] def select_sort(li): for i in range(len(li)): min_1=min(li) new_list.append(min_1) li.remove(min_1) li = [3,2,4,1,5,7,9,6,8] select_sort(li) print(new_list)
2.2双重循环选择排序:
def select_sort(li): for i in range(len(li)): min_loc = i for j in range(i+1,len(li)-1): if li[j]<li[min_loc]: min_loc = j li[i], li[min_loc] = li[min_loc], li[i] li = [1, 2, 54, 67, 11, 24] select_sort(li) print(li)
3.插入排序
3.1插入排序:
def insert_sort(li): for i in range(1,len(li)): tmp = li[i] j=i-1 while j>=0 and li[j]>tmp: li[j+1] = li[j] j-=1 li[j+1] = tmp li = [3,2,4,1,5,7,9,6,8] insert_sort(li) print(li)