Python 算法题
1. 算法题
"""
算法题:
提供一个序列,完成对这个序列的分割。要求分割后的两个序列彼此差值最小
实现函数,返回两个序列
"""
count = 0
def func(i):
i.sort()
global count
count += 1
print('i', i)
print('count', count)
if not i:
return ([], [])
elif len(i) == 1:
return (i[0:], [])
else:
max_num = i[-1]
min_num = i[-2]
max_list, min_list = func(i[:-2])
max_list.append(min_num)
min_list.append(max_num)
print('max_list', max_list)
print('min_list', min_list)
if sum(max_list) >= sum(min_list):
return (max_list, min_list)
else:
return (min_list, max_list)
l = [1, 46, 3, 8, 6, 4561, 4642, 45, 8, 9, 155, 1784]
print(len(l))
l1, l2 = func(l)
print(l1, l2)
2. 快速排序
def quick_sort(alist, start, end):
if start >= end:
return
mid = alist[start]
low = start
high = end
while low < high:
while low < high and alist[high] >= mid:
high -= 1
alist[low] = alist[high]
while low < high and alist[low] < mid:
low += 1
alist[high] = alist[low]
alist[low] = mid
quick_sort(alist, start, low-1)
quick_sort(alist, low+1, end)
alist =[54, 26, 93, 17, 77, 31, 44, 55, 20]
quick_sort(alist,0,len(alist)-1)
print(alist)
3. 冒泡排序
arr = [7, 4, 3, 67, 34, 1, 8]
def bubble_sort(arr):
n = len(arr)
for j in range(0, n - 1):
count = 0
for i in range(0, n - 1 - j):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
count += 1
if count == 0:
return
print(count)
bubble_sort(arr)
print(arr)
arr1 = [1, 3, 4, 7, 8, 34, 67]
bubble_sort(arr1)
print(arr1)
4. 选择排序
在这里插入代码片
5. 希尔排序
在这里插入代码片
6. 堆排序
在这里插入代码片
7. 基数排序
在这里插入代码片