定义一个包含10个数字元素的顺序表,并分别用直接插入排序,选择排序,冒泡排序,希尔排序,快速排序,堆排序进行大到小排序
时间: 2023-07-18 17:46:18 浏览: 77
好的,我来给您示范一下如何用Python语言实现这个问题。
首先,我们需要定义一个包含10个数字元素的顺序表。我们可以用Python中的列表来表示:
```python
lst = [5, 9, 3, 1, 8, 2, 10, 4, 7, 6]
```
接下来,我们可以分别用不同的排序算法来对这个列表进行排序:
1. 直接插入排序
```python
def insert_sort(lst):
n = len(lst)
for i in range(1, n):
j = i - 1
temp = lst[i]
while j >= 0 and lst[j] < temp:
lst[j+1] = lst[j]
j -= 1
lst[j+1] = temp
return lst
result = insert_sort(lst)
print(result)
```
输出结果为:
```
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
```
2. 选择排序
```python
def select_sort(lst):
n = len(lst)
for i in range(n-1):
max_index = i
for j in range(i+1, n):
if lst[j] > lst[max_index]:
max_index = j
lst[i], lst[max_index] = lst[max_index], lst[i]
return lst
result = select_sort(lst)
print(result)
```
输出结果为:
```
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
```
3. 冒泡排序
```python
def bubble_sort(lst):
n = len(lst)
for i in range(n-1):
for j in range(n-i-1):
if lst[j] < lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
return lst
result = bubble_sort(lst)
print(result)
```
输出结果为:
```
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
```
4. 希尔排序
```python
def shell_sort(lst):
n = len(lst)
gap = n // 2
while gap > 0:
for i in range(gap, n):
temp = lst[i]
j = i - gap
while j >= 0 and lst[j] < temp:
lst[j+gap] = lst[j]
j -= gap
lst[j+gap] = temp
gap //= 2
return lst
result = shell_sort(lst)
print(result)
```
输出结果为:
```
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
```
5. 快速排序
```python
def quick_sort(lst):
if len(lst) <= 1:
return lst
pivot = lst[0]
left = [x for x in lst[1:] if x >= pivot]
right = [x for x in lst[1:] if x < pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
result = quick_sort(lst)
print(result)
```
输出结果为:
```
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
```
6. 堆排序
```python
def heap_sort(lst):
def sift_down(start, end):
root = start
while True:
child = 2 * root + 1
if child > end:
break
if child + 1 <= end and lst[child] < lst[child+1]:
child += 1
if lst[root] < lst[child]:
lst[root], lst[child] = lst[child], lst[root]
root = child
else:
break
n = len(lst)
for i in range(n//2-1, -1, -1):
sift_down(i, n-1)
for i in range(n-1, 0, -1):
lst[0], lst[i] = lst[i], lst[0]
sift_down(0, i-1)
return lst
result = heap_sort(lst)
print(result)
```
输出结果为:
```
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
```
阅读全文