简单选择排序python
时间: 2024-06-11 07:03:33 浏览: 17
简单选择排序(Simple Selection Sort)是一种基础的排序算法,它的工作原理是每一次从未排序的部分中找到最小(或最大)的元素,然后放到已排序部分的末尾。在Python中,我们可以使用以下步骤实现简单选择排序:
1. 定义一个未排序的数组(列表)。
2. 遍历整个数组,找到最小的元素。
3. 将找到的最小元素与数组的第一个元素交换位置。
4. 继续遍历剩余的元素,重复步骤2和3,直到所有元素都排序完成。
以下是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 array:", sorted_arr)
相关问题
python简单选择排序
简单选择排序是一种简单直观的排序算法,它的基本思想是每次从待排序序列中选择出最小的元素,然后将其与当前位置的元素交换。通过不断选择最小的元素并交换,最终可以将整个序列排序完成。Python实现简单选择排序的代码如下:
```python
def selectionSort(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]
return arr
```
请注意,上述代码中的arr是待排序的列表。通过调用`selectionSort`函数并传入待排序的列表,可以得到按照升序排列的列表。
选择排序Python
选择排序是一种简单且直观的排序算法,它的主要思想是每次从未排序的部分中选择最小的元素,并将其放在已排序部分的末尾。通过多次迭代,将所有的元素都按照从小到大的顺序排列。
以下是Python实现选择排序的代码:
```python
def selection_sort(array):
for i in range(len(array)-1):
min_index = i
for j in range(i+1, len(array)):
if array[j] < array[min_index]:
min_index = j
if min_index != i:
array[i], array[min_index] = array[min_index], array[i]
return array
if __name__ == '__main__':
array = [10, 17, 50, 7, 30, 24, 27, 45, 15, 5, 36, 21]
print(selection_sort(array))
```
选择排序的时间复杂度为O(n^2),其中n是待排序的元素个数。每一轮排序需要进行n-i次比较,共进行n-1轮排序。
选择排序的一个特点是不管待排序列表的初始状态如何,都不会影响排序的时间复杂度。但由于每次只是交换相邻元素,所以选择排序是一种不稳定的排序算法。
相关推荐
![md](https://img-home.csdnimg.cn/images/20210720083646.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)