How can I fix this function (is_sorted), recursive?

advertisements

How can i fix this (is_sorted) , recursive function? Target: This function takes a string as a input parameter and returns TRUE if characters in the string are in alphabetical ascending order; returns FALSE otherwise. Characters can be lowercase or uppercase.

#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]=='\0'){
        return FALSE;
    }
    else if(strcmp(&str[0],&str[1])<0)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }

    return is_sorted(&str[1]);
}


I see 3 problems within your code, let me first explain the problems in your code before showing a working solution.

First off:

if(str[0]=='\0'){
    return FALSE;
}

Why would a empty string not be sorted? Which elements are out of order? After all it's empty.

Next you don't handle upper/lower case correctly:

if(strcmp(&str[0],&str[1])<0)

strcmp compares the ascii values. Upper case letters got lower values than lower case letters. That means strcmp("G", "a")<0 would return true. You really want to compare lowercase letters. You're also comparing strings not letters.

Lastly you never get to your recursive call.

if(str[0]=='\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.


Now as for my solution:

Bool is_sorted(const char *str){
    if(str[0]=='\0' || str[1] == '\0'){
        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.
}