如何修复这个(is_sorted)递归函数?目标:此函数将字符串作为输入参数,如果字符串中的字符按字母升序排列,则返回 TRUE;否则返回 FALSE。字符可以是小写或大写。
#include<stdio.h>
#define SIZE 50
typedef enum{FALSE,TRUE} Bool;
Bool is_sorted(const char *str);
int main(){
char arr1[SIZE]="aSTYoLPNDeSaFAE";
char arr2[SIZE]="aGjklOvz";
if(is_sorted(arr1)==TRUE){
printf("arr1 (is_sorted) Yes n");
}
else
{
printf("arr1 (is_sorted) No n");
}
if(is_sorted(arr2)==TRUE){
printf("arr2 (is_sorted) Yes n");
}
else
{
printf("arr2 (is_sorted) No n");
}
return 0;
}
Bool is_sorted(const char *str){
if(str[0]==' '){
return FALSE;
}
else if(strcmp(&str[0],&str[1])<0)
{
return TRUE;
}
else
{
return FALSE;
}
return is_sorted(&str[1]);
}
我在您的代码中看到 3 个问题,让我先解释一下您的代码中的问题,然后再展示一个有效的解决方案。
首先:
if(str[0]==' '){
return FALSE;
}
为什么空字符串不排序?哪些元素顺序不正确?毕竟它是空的。
接下来,您没有正确处理大写/小写:
if(strcmp(&str[0],&str[1])<0)
strcmp
比较 ASCII 值。大写字母的值低于小写字母。这意味着strcmp("G", "a")<0
会返回 true。你真的想比较小写字母。您还在比较字符串而不是字母。
最后,你永远不会接到递归调用。
if(str[0]==' '){
return FALSE;
}
else if(strcmp(&str[0],&str[1])<0)
{
return TRUE;
}
else
{
return FALSE; // return if you didn't return in any other condition
}
return is_sorted(&str[1]); // You never get here.
现在至于我的解决方案:
Bool is_sorted(const char *str){
if(str[0]==' ' || str[1] == ' '){
return TRUE; // A single character as well as a empty string are
} // by definition sorted already.
else if(tolower(str[0]) < tolower(str[1))
{
return is_sorted(str + 1); //First two characters are sorted we got to check
} // if the rest are sorted too.
else
{
return FALSE; // If the first two characters aren't sorted the whole
} // string isn't sorted.
}
程序中正确的is_sorted函数应如下所示:
#include <ctype.h>
#include <stdio.h>
Bool is_sorted(const char *str){
if(str[0]==' '){
return TRUE; //the string is empty
}
else if(str[1]==' '){
return TRUE; //the string contains only one character or all letters before NULL are in correct order
}
else if(tolower(str[0])<tolower(str[1])))
{
return is_sorted(&str[1]); //current and next letter are in correct order
}
else
{
return FALSE; //current and next letter are in wrong order, thus whole string is not sorted
}
}