用置换选择排序对51493946 3829146115301485236327413892446583376进行排序并运用数据结构知识编写一个C语言代码。
以下是使用置换选择排序对给定数组进行排序的C语言代码:
#include <stdio.h>
// 函数声明
void swap(int* a, int* b);
void selectionSort(int arr[], int n);
int main() {
// 给定数组
int arr[] = {51,49,39,46,38,29,14,61,15,30,1,48,52,3,63,27,4,13,89,24,46,58,33,76};
int n = sizeof(arr) / sizeof(arr[0]);
// 调用排序函数
selectionSort(arr, n);
// 打印排序后的数组
printf("排序后的数组:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
// 交换数组中的两个元素
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// 使用置换选择排序对数组进行排序
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
swap(&arr[minIndex], &arr[i]);
}
}
运行上述代码,将输出排序后的数组:
排序后的数组:
1 3 4 13 14 15 24 27 29 30 33 38 39 46 46 48 49 51 52 58 61 63 76 89
``
原文地址: https://www.cveoy.top/t/topic/hWM8 著作权归作者所有。请勿转载和采集!