八种排序算法python
时间: 2023-11-07 08:01:26 浏览: 91
八种排序算法的Python实现包括冒泡排序、选择排序、插入排序、快速排序、归并排序、堆排序、计数排序和基数排序。
冒泡排序的Python代码如下:
```
arr = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]
def bubbleSort(arr):
for i in range(1, len(arr)):
for j in range(len(arr)-i):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
print(bubbleSort(arr))
```
选择排序的Python代码如下:
```
arr = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]
def selectionSort(arr):
for i in range(len(arr)-1):
minIndex = i
for j in range(i+1, len(arr)):
if arr[j] < arr[minIndex]:
minIndex = j
if i != minIndex:
arr[minIndex], arr[i] = arr[i], arr[minIndex]
return arr
print(selectionSort(arr))
```
插入排序的Python代码如下:
```
arr = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr
print(insertionSort(arr))
```
其他排序算法的实现可以参考以下资源:
- 快速排序:https://www.geeksforgeeks.org/quick-sort-in-python/
- 归并排序:https://www.geeksforgeeks.org/merge-sort/
- 堆排序:https://www.geeksforgeeks.org/heap-sort/
- 计数排序:https://www.geeksforgeeks.org/counting-sort/
- 基数排序:https://www.geeksforgeeks.org/radix-sort/
阅读全文