实现selection sort排序算法 python
时间: 2024-09-25 17:17:33 浏览: 61
Selection Sort是一种简单直观的排序算法,它的工作原理是每次从未排序的部分找到最小(或最大)的元素,并将其放到已排序部分的末尾。以下是Python实现Selection Sort的步骤:
```python
def selection_sort(arr):
n = len(arr)
# 遍历所有数组元素
for i in range(n):
# 找到剩余未排序部分的最小值
min_index = i
for j in range(i+1, n):
if arr[j] < arr[min_index]:
min_index = j
# 将找到的最小值与当前位置交换
arr[i], arr[min_index] = arr[min_index], arr[i]
return arr
# 示例
arr = [64, 25, 12, 22, 11]
sorted_arr = selection_sort(arr)
print("Sorted array:", sorted_arr)
相关问题
排序算法python实现
下面是Python实现三种常见排序算法的代码:
快速排序算法:
```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)
```
选择排序算法:
```python
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
```
冒泡排序算法:
```python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
```
这些代码分别实现了快速排序、选择排序和冒泡排序算法。你可以根据需要选择其中一种算法来对列表进行排序。
排序算法python
在Python中,有许多不同的排序算法可供选择。以下是一些常见的排序算法的示例:
1. 冒泡排序(Bubble Sort)
冒泡排序是一种简单的排序算法。它重复地遍历要排序的列表,比较相邻的元素,并交换它们,直到整个列表排序完成。
```python
def bubble_sort(arr):
n = len(arr)
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
```
2. 插入排序(Insertion Sort)
插入排序通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
```python
def insertion_sort(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
```
3. 选择排序(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[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
```
还有其他许多排序算法可供选择,如快速排序、归并排序、堆排序等。根据不同的需求和数据规模,选择合适的排序算法是很重要的。
阅读全文
相关推荐















