用c语言起泡法将字符串按ASCⅡ码值从小到大排列
时间: 2023-08-09 07:04:18 浏览: 132
好的,下面是按ASCⅡ码值从小到大排列字符串的C语言代码实现:
```c
#include <stdio.h>
#include <string.h>
void bubbleSort(char str[]) {
int i, j;
int len = strlen(str);
for (i = 0; i < len - 1; i++) {
for (j = 0; j < len - 1 - i; j++) {
if (str[j] > str[j + 1]) {
char temp = str[j];
str[j] = str[j + 1];
str[j + 1] = temp;
}
}
}
}
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
bubbleSort(str);
printf("按ASCⅡ码值排序后的字符串为:%s\n", str);
return 0;
}
```
使用冒泡排序算法,依次比较相邻的字符,如果前面的字符大于后面的字符,则交换它们的位置。重复多次这个过程,直到字符串中所有的字符按ASCⅡ码值从小到大排列。
相关问题
写一个C语言使用起泡法和选择法将字符串按ASCⅡ码从小到大排列,并举例
好的,这是一个比较基础的排序问题,下面是使用起泡法和选择法将字符串按ASCⅡ码从小到大排列的C语言代码:
使用起泡法:
```c
#include <stdio.h>
#include <string.h>
void bubble_sort(char *str, int len) {
int i, j;
char temp;
for (i = 0; i < len - 1; i++) {
for (j = 0; j < len - 1 - i; j++) {
if (str[j] > str[j+1]) {
temp = str[j];
str[j] = str[j+1];
str[j+1] = temp;
}
}
}
}
int main() {
char str[] = "chitgpt";
int len = strlen(str);
bubble_sort(str, len);
printf("排序后的字符串为:%s\n", str);
return 0;
}
```
使用选择法:
```c
#include <stdio.h>
#include <string.h>
void selection_sort(char *str, int len) {
int i, j, min_index;
char temp;
for (i = 0; i < len - 1; i++) {
min_index = i;
for (j = i + 1; j < len; j++) {
if (str[j] < str[min_index]) {
min_index = j;
}
}
if (min_index != i) {
temp = str[i];
str[i] = str[min_index];
str[min_index] = temp;
}
}
}
int main() {
char str[] = "chitgpt";
int len = strlen(str);
selection_sort(str, len);
printf("排序后的字符串为:%s\n", str);
return 0;
}
```
以上代码都是将字符串 "chitgpt" 按ASCⅡ码从小到大排列。
用 C语言编写用冒泡法对输入的 10 个字符按 ASCⅠⅠ码值由小到大的顺序排列
好的,以下是使用冒泡排序方法的 C 语言代码示例:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char chars[10]; // 定义字符数组
char temp; // 用于交换字符的中间变量
printf("请输入 10 个字符,以空格分隔:");
for (int i = 0; i < 10; i++) {
scanf(" %c", &chars[i]); // 读入字符
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10 - i - 1; j++) {
if (chars[j] > chars[j+1]) { // 比较相邻的两个字符
// 如果它们的顺序不对,则交换它们的位置
temp = chars[j];
chars[j] = chars[j+1];
chars[j+1] = temp;
}
}
}
printf("排序后的结果为:");
for (int i = 0; i < 10; i++) {
printf(" %c", chars[i]); // 输出排序后的字符
}
printf("\n");
return 0;
}
```
这个程序要求用户输入 10 个字符,然后使用冒泡排序算法对它们进行排序,并输出结果。冒泡排序算法的基本思想在前面已经解释过了,这里就不再赘述了。需要注意的是,由于 C 语言中字符是以 ASCII 码的形式存储的,所以直接比较字符的大小是可以得到正确结果的。
阅读全文
相关推荐
















