简体   繁体   中英

A program that sorts strings alphabetically without compare.To (Java)

I'm attempting to write a program that is supposed to sort two strings alphabetically, and if s1 comes before s2, return -1, if s1 comes after s2, return 1, and if they are the same word, print 0. So for s1 = "king" and s2 = "kink", it should print -1. I've managed to implement this for words that do not start with the same letter, but for words that do not, such as "king" and "kink" I'm encountering difficulties.

public static int compare(String a, String b)
  {

int comparison = 0;
int c1, c2;
for(int i = 0; i < a.length() && i < b.length(); i++) 
{
    c1 = (int) a.toLowerCase().charAt(i);   
    c2 = (int) b.toLowerCase().charAt(i);   
    comparison = c1 - c2; 

    if(comparison == 0) 
    {
      if(a.length() > b.length())    
         return 1;
      else if (a.length() < b.length())
         return -1;
      else
         return 0;
    }
    else if (comparison > 0)
      return 1;
    else  
      return -1;

}

return comparison;
 }

I feel like the issue is with my for loop, that I'm not allowing it to go through the entire the string, but I'm unsure of how to fix it.

public static int compare(String a, String b) {
    if (a == null) {
        return b == null ? 0 : -1;
    } else if (b == null) {
        return 1;
    }
    String alow = a.toLowerCase();
    String blow = b.toLowerCase();
    int len = Math.min(a.length(), b.length());
    for (int i = 0; i < len; i++) {
        int d = alow.charAt(i) - blow.charAt(i);
        if (d != 0) {
            return d < 0 ? -1 : 1;
        }
    }
    int diff = a.length() - len;
    if (diff != 0) {
        return diff < 0 ? -1 : 1;
    }
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM