十大排序算法PYTHON
时间: 2024-09-13 16:00:21 浏览: 45
python十大排序算法
十大排序算法是指在数据结构与算法领域中,一些常用的、高效的排序方法。在Python中实现这些算法通常非常直观和简洁。以下是十大排序算法及其在Python中的简单实现示例:
1. 冒泡排序(Bubble Sort)
```python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
```
2. 选择排序(Selection Sort)
```python
def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[min_idx] > arr[j]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
```
3. 插入排序(Insertion Sort)
```python
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
```
4. 希尔排序(Shell Sort)
```python
def shell_sort(arr):
n = len(arr)
gap = n//2
while gap > 0:
for i in range(gap, n):
temp = arr[i]
j = i
while j >= gap and arr[j - gap] > temp:
arr[j] = arr[j - gap]
j -= gap
arr[j] = temp
gap //= 2
```
5. 归并排序(Merge Sort)
```python
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
```
6. 快速排序(Quick Sort)
```python
def quick_sort(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 quick_sort(left) + middle + quick_sort(right)
```
7. 堆排序(Heap Sort)
```python
def heapify(arr, n, i):
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)
def heap_sort(arr):
n = len(arr)
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)
```
8. 计数排序(Counting Sort)
```python
def counting_sort(arr, exp):
n = len(arr)
output = [0] * n
count = [0] * (10**exp)
for i in range(n):
index = arr[i] // exp
count[index % 10**exp] += 1
for i in range(1, 10**exp):
count[i] += count[i - 1]
i = n - 1
while i >= 0:
output[count[arr[i] // exp] - 1] = arr[i]
count[arr[i] // exp] -= 1
i -= 1
for i in range(len(arr)):
arr[i] = output[i]
```
9. 桶排序(Bucket Sort)
```python
def bucket_sort(arr):
buckets = [[] for _ in range(len(arr))]
for i in range(len(arr)):
bucket = int(arr[i] * len(buckets))
buckets[bucket].append(arr[i])
for i in range(len(buckets)):
buckets[i] = sorted(buckets[i])
return [x for bucket in buckets for x in bucket]
```
10. 基数排序(Radix Sort)
```python
def radix_sort(arr):
max_value = max(arr)
exp = 1
while max_value // exp > 0:
counting_sort(arr, exp)
exp *= 10
```
这些排序算法在Python中的实现都非常直观,但在实际应用中可能需要根据数据的特性和使用场景来选择最合适的排序算法,以达到最优的性能。
阅读全文