defmaopao(array):for i inrange(len(array)):for j inrange(len(array)- i -1):if array[j]> array[j +1]:
array[j], array[j +1]= array[j +1], array[j]return array
选择排序
defxuanze(array):for i, num inenumerate(array):
min_index = i
for j inrange(i +1,len(array)):if array[min_index]> array[j]:
min_index = j
if min_index != i:
array[i], array[min_index]= array[min_index], array[i]return array
插入排序
defcharu(array):
result =[]for index, num inenumerate(array):for i inrange(index):if result[i]> num:
result.insert(i, num)breakelse:
result.append(num)return result
希尔排序
defshell(array):
length =len(array)//2while length !=1:
array = charu_tap(array, length)
length = length //2else:return charu_tap(array, length)defcharu_tap(array, tap):
result =[]for index, num inenumerate(array):if index // tap >=1:
strat = index % tap
for i inrange(strat, index, tap):if result[i]> num:
result.append(num)
result[i], result[index]= result[index], result[i]breakelse:
result.append(num)else:
result.append(num)return result
归并排序
defmerge_sort(lst, fx=True):iflen(lst)<=1:# 当列表元素只有一个的时候,直接返回return lst
mid =len(lst)//2
left = lst[:mid]
right = lst[mid:]
starttime = time.time()
left = merge_sort(left,not fx)
right = merge_sort(right,not fx)# 递归的进行排序
result =[]while left and right:if(left[-1]< right[-1])== fx:
result.append(left.pop())else:
result.append(right.pop())if left:if fx andlen(left)==1:
result.extend(left)else:
left.reverse()
result.extend(left)if right:if fx andlen(right)==1:
result.extend(right)else:
right.reverse()
result.extend(right)return result
# 返回排序后的结果
快速排序
classSort:
@staticmethoddefquick_sort(sort_list, fir=None, last=None):"""
快速排序
:param sort_list:
:param fir:
:param last:
:return:
"""if fir isNoneand last isNone:
fir =0
last =len(sort_list)-1if fir < last:
sp = Sort._swap_position(sort_list, fir, last)
Sort.quick_sort(sort_list, fir, sp -1)
Sort.quick_sort(sort_list, sp +1, last)
@staticmethoddef_swap_position(arr, fir, last):
pv = arr[fir]
lm = fir +1
rm = last
do =Falsewhilenot do:while lm <= rm and arr[lm]<= pv:
lm = lm +1while arr[rm]>= pv and rm >= lm:
rm = rm -1if rm < lm:
do =Trueelse:
temp = arr[lm]
arr[lm]= arr[rm]
arr[rm]= temp
temp = arr[fir]
arr[fir]= arr[rm]
arr[rm]= temp
return rm
冒泡排序def maopao(array): for i in range(len(array)): for j in range(len(array) - i - 1): if array[j] > array[j + 1]: array[j], array[j + 1] = array[j + 1], array[j] return array选择排序def xuanze(array): for