用C语言程序编程出:设数组a中有n(n<10)个字符元素,用选择排序法将这n个元素按照ASCII码值从小到大排序。 样例输入 :5 bDfea 样例输出: Dabef
时间: 2024-05-16 20:12:35 浏览: 69
以下是C语言程序代码:
```c
#include <stdio.h>
void selectionSort(char arr[], int n)
{
int i, j, min_idx;
char temp;
// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
int main()
{
int n, i;
char a[10];
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter the elements: ");
for(i = 0; i < n; i++)
{
scanf(" %c", &a[i]);
}
selectionSort(a, n);
printf("Sorted array: ");
for(i = 0; i < n; i++)
{
printf("%c", a[i]);
}
printf("\n");
return 0;
}
```
代码实现了选择排序算法,将字符数组按照ASCII码值从小到大排序,可以通过输入字符元素的个数和字符元素本身进行测试。
阅读全文