Explain the editorial in detais

i didnt get the compareto function of the editorial explain in detail

Hi @kashishsoni,
See you have to swap the values only when a following condition is true . Therefore based on the condition we have to sort firstly on the basis of the value of the character. hence we are trying to compare each character one by one (For ex-a<b) and the while loop enclosing them is trying to take care that we do not exceed the length of the string.Now if the string are same for example bat and batman then the result will be on the basis of the length hence the if and else statement in the last is taking care of that.

can you please explain the running of this code in detail like step by step

nt compareTo(string s1, string s2) {

    int i = 0;      

    while (i < s1.length() && i < s2.length()) {

        if (s1[i] > s2[i]) {

            return 1;
        } else if (s1[i] < s2[i]) {
            return -1;
        }
        i++;

    }

    if (s1.length() > s2.length()) {
        return -1;
    } else {
        return 1;
    }

}

Two strings are taken s1 and s2 . And hence at first we ensure that none of the string has been fully navigated by this loop -> " while (i < s1.length() && i < s2.length()) " .
then if s1 has ith character greater than jth character of string s2 then we have a winner therefore a return 1 statement.
otherwise if it is less than then s2 wins and we send return -1.
But in the case of bat and batman we actually reach the end of one string while the other is still present . Hence we then compare the length of the two string . therefore the remaining two if and else statements. -> if (s1.length() > s2.length()) {
return -1;
} else {
return 1;
}

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.