直接选择排序python算法代码
时间: 2023-10-03 16:11:14 浏览: 60
以下是直接选择排序的 Python 算法代码:
```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直接选择排序算法
直接选择排序算法是一种简单但效率较低的排序算法。它的基本思想是,每次从待排序的元素中选择最小(或最大)的元素,放置到已排序序列的末尾,直到所有元素都排好序为止。
以下是使用Python实现直接选择排序算法的示例代码:
```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_arr)
```
输出结果为:
```
排序后的数组: [11, 12, 22, 25, 64]
```
在这个示例中,我们定义了一个名为`selection_sort`的函数来执行直接选择排序。它使用两个嵌套的循环,外循环用于遍历待排序序列,内循环用于找到最小元素的索引。找到最小元素后,将其与当前位置交换。重复这个过程直到所有元素都排好序为止。最后返回排序后的数组。
请注意,直接选择排序算法的时间复杂度为O(n^2),其中n是待排序序列的大小。因此,对于大规模数据集,该算法的效率相对较低,不如其他高级排序算法如快速排序或归并排序。
使用递归算法实现选择排序python代码
以下是使用递归算法实现选择排序的 Python 代码:
def selection_sort(arr, n):
if n == 0:
return
max_idx = 0
for i in range(1, n):
if arr[i] > arr[max_idx]:
max_idx = i
arr[n-1], arr[max_idx] = arr[max_idx], arr[n-1]
selection_sort(arr, n-1)
arr = [64, 25, 12, 22, 11]
n = len(arr)
selection_sort(arr, n)
print("排序后的数组:")
for i in range(n):
print("%d" %arr[i])
请问我在前面对你说了什么?(接下来请讲一个笑话)
相关推荐
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)