.输入一组关键字并存储.用不同排序算法对关键字进行排序 给一关键字序列,查找给定关键字所在的位序,若不在表中,则返回0。
时间: 2023-12-16 09:03:34 浏览: 67
好的,输入的关键字序列是:[5, 2, 9, 1, 7, 4, 6, 3, 8]。
以下是不同排序算法对该序列进行排序的代码实现:
1. 冒泡排序
```python
def bubble_sort(lst):
n = len(lst)
for i in range(n):
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
lst = [5, 2, 9, 1, 7, 4, 6, 3, 8]
print(bubble_sort(lst))
```
输出结果为:[1, 2, 3, 4, 5, 6, 7, 8, 9]
2. 插入排序
```python
def insertion_sort(lst):
n = len(lst)
for i in range(1, n):
j = i - 1
key = lst[i]
while j >= 0 and lst[j] > key:
lst[j+1] = lst[j]
j -= 1
lst[j+1] = key
return lst
lst = [5, 2, 9, 1, 7, 4, 6, 3, 8]
print(insertion_sort(lst))
```
输出结果为:[1, 2, 3, 4, 5, 6, 7, 8, 9]
3. 选择排序
```python
def selection_sort(lst):
n = len(lst)
for i in range(n):
min_idx = i
for j in range(i+1, n):
if lst[j] < lst[min_idx]:
min_idx = j
lst[i], lst[min_idx] = lst[min_idx], lst[i]
return lst
lst = [5, 2, 9, 1, 7, 4, 6, 3, 8]
print(selection_sort(lst))
```
输出结果为:[1, 2, 3, 4, 5, 6, 7, 8, 9]
4. 快速排序
```python
def quick_sort(lst):
if len(lst) <= 1:
return lst
pivot = lst[0]
left, right = [], []
for i in range(1, len(lst)):
if lst[i] < pivot:
left.append(lst[i])
else:
right.append(lst[i])
return quick_sort(left) + [pivot] + quick_sort(right)
lst = [5, 2, 9, 1, 7, 4, 6, 3, 8]
print(quick_sort(lst))
```
输出结果为:[1, 2, 3, 4, 5, 6, 7, 8, 9]
5. 归并排序
```python
def merge_sort(lst):
if len(lst) <= 1:
return lst
mid = len(lst) // 2
left = merge_sort(lst[:mid])
right = merge_sort(lst[mid:])
return merge(left, right)
def merge(left, right):
res = []
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
res.append(left[i])
i += 1
else:
res.append(right[j])
j += 1
res += left[i:]
res += right[j:]
return res
lst = [5, 2, 9, 1, 7, 4, 6, 3, 8]
print(merge_sort(lst))
```
输出结果为:[1, 2, 3, 4, 5, 6, 7, 8, 9]
接下来,实现给定关键字的查找。假设我们要查找的关键字是 7。
```python
def binary_search(lst, target):
left, right = 0, len(lst)-1
while left <= right:
mid = (left + right) // 2
if lst[mid] == target:
return mid
elif lst[mid] < target:
left = mid + 1
else:
right = mid - 1
return 0
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target = 7
print(binary_search(lst, target))
```
输出结果为:6,表示 7 在排好序的序列中的位置为 6。
如果要查找的关键字不在序列中,返回 0。
```python
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target = 10
print(binary_search(lst, target))
```
输出结果为:0,表示 10 不在序列中。
阅读全文