用选择法对十个整数排序
时间: 2023-11-21 19:57:27 浏览: 82
选择排序的基本思路是将待排序序列分为已排序和未排序两部分,每次从未排序中选出最小(或最大)的元素,放到已排序的末尾。重复以上步骤,直到未排序中没有元素。
以下是使用选择排序对十个整数排序的示例代码:
```python
def selection_sort(arr):
n = len(arr)
for i in range(n-1):
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
arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
sorted_arr = selection_sort(arr)
print(sorted_arr)
```
输出结果为:`[1, 1, 2, 3, 3, 4, 5, 5, 6, 9]`。
相关问题
用选择法对10个整数排序
好的,下面是使用选择排序算法对10个整数进行排序的示例代码:
```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]
# 测试
arr = [64, 25, 12, 22, 11, 75, 90, 8, 38, 2]
selection_sort(arr)
print("排序后的数组:")
for i in range(len(arr)):
print("%d" %arr[i])
```
输出结果:
```
排序后的数组:
2
8
11
12
22
25
38
64
75
90
```
以上代码中,selection_sort 函数接收一个列表作为参数,然后使用两层循环,每次找到最小的元素,并将其与当前位置的元素交换。最终得到的就是排序好的数组。
用选择法对 10 个 整数排序
好的,以下是使用选择排序算法对 10 个整数进行排序的示例代码(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
# 测试
arr = [64, 25, 12, 22, 11, 99, 88, 9, 72, 45]
print("原数组:", arr)
print("排序后的数组:", selection_sort(arr))
```
输出结果:
```
原数组: [64, 25, 12, 22, 11, 99, 88, 9, 72, 45]
排序后的数组: [9, 11, 12, 22, 25, 45, 64, 72, 88, 99]
```
该算法的基本思路是,首先在未排序的序列中找到最小元素,然后将其放到序列的起始位置。接着,再从剩余未排序的元素中继续寻找最小元素,然后放到已排序的序列的末尾。重复这个过程,直到整个序列都排好序。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)