题目要求对关键字序列k={12,45,21,12,30,2,68,33}进行直接插入排序、希尔排序、冒泡排序、快速排序、简单选择排序算法进行排序,要有菜单项进行选择。
时间: 2024-01-08 14:02:05 浏览: 41
排序算法汇总_选择排序_,直接插入排序,冒泡排序,希尔排序,快速排序,堆排序定义.pdf
好的,我可以帮您实现这个算法的排序菜单。以下是我的代码实现:
```python
def direct_insertion_sort(k):
for i in range(1, len(k)):
temp = k[i]
j = i - 1
while j >= 0 and temp < k[j]:
k[j+1] = k[j]
j -= 1
k[j+1] = temp
return k
def shell_sort(k):
gap = len(k) // 2
while gap > 0:
for i in range(gap, len(k)):
temp = k[i]
j = i - gap
while j >= 0 and temp < k[j]:
k[j+gap] = k[j]
j -= gap
k[j+gap] = temp
gap //= 2
return k
def bubble_sort(k):
for i in range(len(k)-1):
for j in range(i, len(k)):
if k[i] > k[j]:
k[i], k[j] = k[j], k[i]
return k
def quick_sort(k):
if len(k) <= 1:
return k
pivot = k[len(k) // 2]
left = [x for x in k if x < pivot]
middle = [x for x in k if x == pivot]
right = [x for x in k if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
def selection_sort(k):
for i in range(len(k)):
min_index = i
for j in range(i+1, len(k)):
if k[j] < k[min_index]:
min_index = j
k[i], k[min_index] = k[min_index], k[i]
return k
while True:
print("请选择要进行的排序算法:")
print("1) 直接插入排序")
print("2) 希尔排序")
print("3) 冒泡排序")
print("4) 快速排序")
print("5) 简单选择排序")
print("0) 退出程序")
choice = input()
if choice == "1":
sorted_k = direct_insertion_sort(k)
elif choice == "2":
sorted_k = shell_sort(k)
elif choice == "3":
sorted_k = bubble_sort(k)
elif choice == "4":
sorted_k = quick_sort(k)
elif choice == "5":
sorted_k = selection_sort(k)
elif choice == "0":
print("程序已退出")
break
else:
print("请输入正确的选项")
if choice in ["1", "2", "3", "4", "5"]:
print("排序后的序列为:", sorted_k)
```
您需要输入菜单上列出的选项来选择排序算法,然后列表将根据你选择的算法进行排序。请注意,您需要手动输入要排序的数字,因为您没有在问题中提供它们的值。
阅读全文