利用学过的4种排序方法(直接插入排序(改进前,改进后),简单选择排序,冒泡排序),实现对输入整数的排序输出,显示整个排序过程。
时间: 2023-08-04 16:06:36 浏览: 58
好的,以下是利用4种排序方法实现对输入整数的排序输出,并显示整个排序过程的Python代码:
1. 直接插入排序(改进前):
```python
def insert_sort(nums):
n = len(nums)
for i in range(1, n):
j = i - 1
while j >= 0 and nums[j] > nums[j+1]:
nums[j], nums[j+1] = nums[j+1], nums[j]
j -= 1
print(nums)
return nums
nums = [5, 3, 8, 6, 4]
print("原始序列:", nums)
print("排序过程:")
insert_sort(nums)
print("排序结果:", nums)
```
2. 直接插入排序(改进后):
```python
def insert_sort(nums):
n = len(nums)
for i in range(1, n):
j = i - 1
if nums[i] < nums[j]:
temp = nums[i]
nums[i] = nums[j]
j -= 1
while j >= 0 and nums[j] > temp:
nums[j+1] = nums[j]
j -= 1
nums[j+1] = temp
print(nums)
return nums
nums = [5, 3, 8, 6, 4]
print("原始序列:", nums)
print("排序过程:")
insert_sort(nums)
print("排序结果:", nums)
```
3. 简单选择排序:
```python
def select_sort(nums):
n = len(nums)
for i in range(n-1):
min_index = i
for j in range(i+1, n):
if nums[j] < nums[min_index]:
min_index = j
if min_index != i:
nums[i], nums[min_index] = nums[min_index], nums[i]
print(nums)
return nums
nums = [5, 3, 8, 6, 4]
print("原始序列:", nums)
print("排序过程:")
select_sort(nums)
print("排序结果:", nums)
```
4. 冒泡排序:
```python
def bubble_sort(nums):
n = len(nums)
for i in range(n-1):
for j in range(n-i-1):
if nums[j] > nums[j+1]:
nums[j], nums[j+1] = nums[j+1], nums[j]
print(nums)
return nums
nums = [5, 3, 8, 6, 4]
print("原始序列:", nums)
print("排序过程:")
bubble_sort(nums)
print("排序结果:", nums)
```
以上代码中,我们定义了4个排序方法:直接插入排序(改进前、改进后)、简单选择排序和冒泡排序。在排序过程中,我们使用了print()函数来输出每一轮排序后的序列结果,从而展示整个排序过程。最终,我们输出排序结果,得到了排序后的整数序列。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)