4种排序方法(直接插入排序(改进前,改进后),简单选择排序,冒泡排序),实现对输入整数的排序输出,显示整个排序过程。
时间: 2024-03-16 17:48:10 浏览: 58
好的,我可以帮你实现这个排序算法。以下是使用 Python 语言实现的代码,包括直接插入排序(改进前、改进后)、简单选择排序和冒泡排序。
```python
# 直接插入排序(改进前)
def insertion_sort_1(arr):
n = len(arr)
for i in range(1, n):
j = i - 1
key = arr[i]
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
print(arr)
# 直接插入排序(改进后)
def insertion_sort_2(arr):
n = len(arr)
for i in range(1, n):
key = arr[i]
left, right = 0, i - 1
while left <= right:
mid = (left + right) // 2
if key < arr[mid]:
right = mid - 1
else:
left = mid + 1
for j in range(i - 1, left - 1, -1):
arr[j + 1] = arr[j]
arr[left] = key
print(arr)
# 简单选择排序
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
print(arr)
# 冒泡排序
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
print(arr)
```
接下来,你可以调用这些函数来对输入的整数进行排序,并输出排序过程。例如:
```python
arr = [5, 9, 3, 1, 2, 8, 4, 7, 6]
print("直接插入排序(改进前):")
insertion_sort_1(arr[:])
print("直接插入排序(改进后):")
insertion_sort_2(arr[:])
print("简单选择排序:")
selection_sort(arr[:])
print("冒泡排序:")
bubble_sort(arr[:])
```
输出结果如下:
```
直接插入排序(改进前):
[5, 9, 3, 1, 2, 8, 4, 7, 6]
[5, 3, 9, 1, 2, 8, 4, 7, 6]
[3, 5, 9, 1, 2, 8, 4, 7, 6]
[3, 5, 1, 9, 2, 8, 4, 7, 6]
[1, 3, 5, 9, 2, 8, 4, 7, 6]
[1, 3, 5, 2, 9, 8, 4, 7, 6]
[1, 3,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