实现冒泡排序,快速排序,归并排序的递归和非递归 要求从测试数据文件中读入数据,执行后输出的结果文件中
时间: 2024-09-30 11:12:14 浏览: 31
用C语言实现从文本文件中读取数据后进行排序的功能
实现排序算法(如冒泡排序、快速排序和归并排序)的递归和非递归版本,通常涉及以下几个步骤:
**冒泡排序(递归和非递归)**
1. **非递归实现**:
```python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
if not swapped: # 如果一趟没有交换,则数组已排序
break
```
2. **递归实现**:
```python
def bubble_sort_recursive(arr, n):
if n <= 1:
return
for i in range(n-1):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
bubble_sort_recursive(arr, n-1)
```
**快速排序(递归和非递归)**
1. **非递归实现**:
```python
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
```
2. **递归实现**:
```python
def quicksort_recursive(arr):
if len(arr) <= 1:
return arr
pivot_index = len(arr) // 2
pivot, smaller, larger = arr[pivot_index], [], []
for element in arr:
if element < pivot:
smaller.append(element)
elif element > pivot:
larger.append(element)
return quicksort_recursive(smaller) + [pivot] + quicksort_recursive(larger)
```
**归并排序(递归和非递归)**
1. **非递归实现**:
```python
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
return merge(merge_sort(left_half), merge_sort(right_half))
def merge(left, right):
merged = []
left_index, right_index = 0, 0
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
merged.append(left[left_index])
left_index += 1
else:
merged.append(right[right_index])
right_index += 1
merged.extend(left[left_index:])
merged.extend(right[right_index:])
return merged
```
2. **递归实现**:
```python
def merge_sort_recursive(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort_recursive(arr[:mid])
right = merge_sort_recursive(arr[mid:])
return merge(left, right)
```
在实际操作中,你需要将上述代码嵌套到文件读取和写入的框架中,比如Python的`with open('input.txt', 'r') as input_file`来读取数据,`with open('output.txt', 'w') as output_file`来写入结果。
阅读全文