Search code examples
javastringsortingwhile-loopcompareto

Alphabetize strings (without using compareTo Method)


I'm trying to sort an array of strings without using compareTo(), but I am getting stuck on my while loop. Is there a way to alphabetically sort strings without using compareTo() or Arrays.sort()?

public class mycode 
{

    public static void main(String[ ] args)
    {
            String[ ] ar = {"hello", "java", "elephant", "array"};
            mycode.display(ar);
            mycode.bubbleSort(ar);
            mycode.display(ar);
    }
    static void display(String[] ar)
    {
        System.out.println("***********************");
        for(int i = 0; i < ar.length; i++)
        {
            System.out.println(ar[i]);
        }
        System.out.println("***********************");

    }
    static void bubbleSort(String[] ar)
    {
        int theFollower;
        for(int currStart = 1; currStart < ar.length; currStart++)
        {
            theFollower = currStart;
            while(theFollower != 0 && ar[theFollower] < ar[theFollower - 1]) //this is where my problem is
            {
                String swap = ar[theFollower];
                ar[theFollower] = ar[theFollower - 1];
                ar[theFollower - 1] = swap;
                theFollower--;
            }
        }
    }

}

Alphabetization is my goal, so my output would be the following

***********************
hello
java
elephant
array
***********************
***********************
array
elephant
hello
java
***********************

I added this method using the idea that was suggested, but I am unsure what I would put in place to run through the index of the string

    int alphabetize(String a, String b)
    {
    String A = a.toLowerCase();
    String B = b.toLowerCase();
    if (A < B)
    {
        return -1;
    }
    else if (A > B)
    {
        return  1;
    }
    else
    {
    }
    }

Solution

  • I'm assuming this is homework, since the obvious way is just to use compareTo(), so I'll give you a hint on how to write your own method to do the comparison. You want something with signature

    int compareStrings(String s, String t);
    

    that returns -1 or 0 or 1 depending on whether s is alphabetically before, equal to or after t in the alphabet.

    Go through the two Strings character by character, and at each stage, if the character from s is less than that of t (here you can use <) then return -1; if it's greater, then return 1; if they're equal, keep going.

    If you run out of characters in s but still have some in t, then return -1, and if it's the other way round then return 1. If you run out of both at the same time, return 0.