实现简单选择排序的功能
时间: 2023-08-28 12:36:25 浏览: 36
好的,以下是简单选择排序的实现代码(使用 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
```
这个函数接受一个列表作为参数,返回一个排序后的列表。算法的思路是从未排序的序列中选择最小的元素,放到已排序的序列的末尾。时间复杂度为 O(n^2)。
相关问题
用c语言实现简单选择排序的功能
下面是用C语言实现简单选择排序的代码:
```c
#include <stdio.h>
void selection_sort(int array[], int n) {
int i, j, min_idx;
// 执行 n-1 轮选择操作
for (i = 0; i < n - 1; i++) {
// 找到 [i, n-1] 范围内的最小元素下标
min_idx = i;
for (j = i + 1; j < n; j++) {
if (array[j] < array[min_idx]) {
min_idx = j;
}
}
// 交换 array[i] 和 array[min_idx]
int temp = array[i];
array[i] = array[min_idx];
array[min_idx] = temp;
}
}
int main() {
int array[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
int n = sizeof(array) / sizeof(array[0]);
selection_sort(array, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", array[i]);
}
printf("\n");
return 0;
}
```
这个函数接受一个整数数组和数组长度作为参数,然后使用简单选择排序算法对数组进行排序。该算法的时间复杂度为O(n^2)。
要求用c语言实现数组简单选择排序的功能
好的,以下是用C语言实现数组简单选择排序的代码:
```c
#include <stdio.h>
void simpleSelectionSort(int arr[], int n) {
int i, j, minIndex, temp;
for (i = 0; i < n - 1; i++) {
minIndex = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
int main() {
int arr[] = {3, 5, 1, 8, 2, 7, 4, 6};
int n = sizeof(arr) / sizeof(arr[0]);
simpleSelectionSort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
以上代码中,`simpleSelectionSort` 函数使用了简单选择排序算法对数组进行排序。该算法每次从未排序的部分中找到最小的元素,然后将其放到已排序的部分的末尾。在每一轮排序中,会在未排序的部分中找到最小的元素,并与未排序部分的第一个元素交换位置。最终,数组就会被排序完成。
在 `main` 函数中,我们定义了一个数组 `arr`,并使用 `sizeof` 函数获取了数组的长度。然后,我们调用 `simpleSelectionSort` 函数对数组进行排序,并输出排序后的结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)