c - 为什么具有递减阶段的冒泡排序不起作用?
问题描述
我是 C 的初学者,我正在尝试创建一个程序,在该程序中,我在冒泡排序算法的帮助下根据单词的 ASCII 总和对处于递减阶段的单词进行排序(例如,ASCII 总和最大的单词将去first 和 last 将是具有最小 ASCII 和的单词 - 这就是我使用 strcmp 比较单词的原因)但是当我打印单词时,我的冒泡排序算法不起作用出了什么问题?
我的代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void swap(char **xp, char **yp)
{
char **temp;
temp= xp;
*xp = *yp;
yp = temp;
}
void bubbleSort(char **arr, int n)
{
int i, j;
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++)
if (strcmp(arr[j] , arr[j+1])>=0)
swap(&arr[j], &arr[j+1]);
}
int main ()
{
char *p[5]={"Manolas","tikinio","youssef el arabi"};
bubbleSort(p,3);
char **p1;
p1=p;
for(p1=p ; *p1 ; p1++)
{
printf("\nthe words are : %s", *p1);
}
return 0;
}
解决方案
strcmp(arr[j], arr[j+1]) >= 0
总是false
因为输入字符串的顺序已经正确,strcmp()
这并不像您想象的那样起作用。所以swap()
永远不会被调用。
swap()
printf()
在任何情况下都被错误地定义(并且在我尝试它时导致了段错误 - 只有在排序完成后才被调用时才令人困惑):
void swap(char **xp, char **yp)
{
char* temp = *xp;
*xp = *yp;
*yp = temp;
}
您的 `main() 例程被不必要地混淆了,建议:
char* p[] = {"Manolas","tikinio","youssef el arabi"} ;
const int count = sizeof(p) / sizeof(*p) ;
bubbleSort( p, count );
printf( "The words are:\n" ) ;
for( int i = 0; i < count; i++ )
{
printf( "%s\n", p[i] ) ;
}
不满足您指定的排序条件strcmp()
。 strcmp()
返回:
<0 the first character that does not match has a lower value in ptr1 than in ptr2
0 the contents of both strings are equal
>0 the first character that does not match has a greater value in ptr1 than in ptr2
您需要不同的比较功能:
int acsiiSumCmp( const char* a, const char* b )
{
unsigned sum_a = 0 ;
unsigned sum_b = 0 ;
for( int i = 0; a[i] != 0; i++ ) sum_a += (unsigned char)a[i] ;
for( int i = 0; b[i] != 0; i++ ) sum_b += (unsigned char)b[i] ;
return sum_a - sum_b ;
}
当总和a
大于时返回 >1 b
,这样要实现您指定的排序,您需要:
if( acsiiSumCmp( arr[j] , arr[j + 1] ) < 0 )
{
swap( &arr[j], &arr[j + 1] ) ;
}
请注意,当条款相等时,无需交换>=
或<=
与您拥有的一样,只是<
或>
取决于所需的顺序。
最后一点“const-correctness”在这里不会出错,如下所示:
void swap( const char**xp, const char** yp )
^^^^^ ^^^^^
void bubbleSort( const char** arr, int n)
^^^^^
const char* p[] = { "ZZ", "Manolas","tikinio","youssef el arabi", "AA" } ;
^^^^^
推荐阅读
- angular - 开玩笑,TypeScript:缺少分号错误
- xaml - Xamarin 表单 - ListView - 数组 - 标题
- ansible - Ansible - 如何遍历多个主机并在找到正确答案时停止?
- c# - HttpClient 属性未通过 DI 传递
- html - 如何使用 NodeJS 服务器和 Angular Front 获取图像?
- java - 无效参数的 Spring Rest Controller 异常处理
- keras - 张量板图像未更新
- sql - 当前脚本的可用选项 > 需要表或视图 (SQL Server)
- python - 使用python进行渐晕校正
- java - 将变量从表示层传递到逻辑层