c语言实现简单选择排序算法
时间: 2024-01-05 07:03:59 浏览: 45
以下是C语言实现简单选择排序算法的代码:
```c
// 交换两个数据
void Swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// 选择排序
void SelectSort(int* arr, int size) {
int i = 0;
for (i = 0; i < size-1; i++) {
int min = i;
int j = 0;
for (j = i+1; j < size; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
Swap(&arr[i], &arr[min]);
}
}
```
相关问题
c语言实现选则排序算法
选择排序是一种简单的排序算法,基本思想是将待排序序列分为已排序和未排序两部分,每次从未排序部分中选择最小的元素放到已排序部分的末尾,直到未排序部分为空。
以下是C语言实现选择排序算法的步骤:
1. 定义一个函数,接受待排序数组和数组长度作为参数;
2. 使用for循环遍历整个数组,每次选取未排序部分的最小值,并将其与当前位置进行交换;
3. 重复以上步骤,直到整个数组有序。
下面是C语言实现选择排序算法的代码示例:
```
void selectionSort(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;
}
}
```
c语言编写程序实现简单选择排序算法
下面是用 C 语言编写的简单选择排序算法的实现:
```c
#include <stdio.h>
void selection_sort(int arr[], int n) {
int i, j, min_idx;
for (i = 0; i < n - 1; i++) {
min_idx = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
selection_sort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
简单选择排序的原理是每次选择最小的元素放到数组的最前面,然后在剩下的元素中继续选择最小的元素放到已排序部分的后面,直到整个数组都被排序。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)