写一个python选择排序算法。
时间: 2023-02-23 14:40:40 浏览: 56
选择排序算法是一种简单的排序算法,其基本思想是:每一趟从待排序的数列中选出最小(或最大)的一个元素,存放到序列的起始位置,直到全部待排序的数据元素排完。
下面是 Python 代码实现:
```
def selection_sort(arr):
for i in range(len(arr) - 1):
# 寻找最小值的索引
min_index = i
for j in range(i + 1, len(arr)):
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_arr)
```
输出:
```
[11, 12, 22, 25, 64]
```
相关问题
请写一个python的排序算法
以下是一个Python的快速排序算法的实现:
```python
def quick_sort(arr):
# 如果数组长度小于2,则无需排序,直接返回
if len(arr) < 2:
return arr
else:
# 选择数组中的第一个元素作为基准值
pivot = arr[0]
# 将小于基准值的数放在左边,大于基准值的数放在右边
less = [i for i in arr[1:] if i <= pivot]
greater = [i for i in arr[1:] if i > pivot]
# 递归排序左右两边的子数组并将结果合并
return quick_sort(less) + [pivot] + quick_sort(greater)
```
这个快速排序算法的时间复杂度为O(nlogn),它是一种高效的排序算法。
写一个python冒泡排序算法
以下是一个简单的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]
return arr
```
该算法采用了嵌套循环的方式来实现排序。外层循环控制排序的轮数,内层循环对相邻的元素进行比较和交换,使较大的元素逐渐往后移动。最终,通过多轮比较和交换,数组按照升序排列。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)