3

Hi all I am very new for the Java. I would like to sort below array of strings as per LastName then on FirstName without use of any API i.e. I am not supposed to use Arrays.sort() , compareTo(), equals() etc..

Input array String

String [][]name={{"Jen","Eric"},
              {"Brain","Adams"},
              {"Jon","Methew"},
              {"Antino","Ronald"},
              {"Cris","Ronald"}
             };

my out put should be like.

             Brain,Adams
             Jen,Eric
             Jon,Methew
             Antino,Ronald
             Cris,Ronald

Please Help.

public class StringArraySort {

public static void main(String[] args) {



    //System.out.println(str.length);
    String [][]name={{"Jen","Eric"},
            {"Brain","Adams"},
            {"Jon","Methew"},
            {"Antino","Ronald"},
              {"Cris","Ronald"}
           };

    String []str1= new String [name.length];
    String []str2= new String [name.length];

    for(int i=1;i<name.length;i++)
    {
        int j=i;
        str1[i]=name[i][j];
        str2[i]=name[i-1][j];
        //System.out.println(str1[i]+" "+str2[i]);


    }

    /*for(String tmp:name)
    {
        char a[] = new char[tmp.length()] ;
        //System.out.println(tmp);
        for(int i=0;i<tmp.length();i++)
        {
            a[i]=tmp.charAt(i);
            System.out.println(a[i]);
        }
    }*/
}

}

3
  • Using bogosort would be easiest. Shuffle your array randomly and check if it is sorted. If not, repeat. en.wikipedia.org/wiki/Bogosort Commented Aug 26, 2015 at 7:30
  • 1
    Writing own equals() method wouldnt be very hard, but you can start comparing strings at the char level. You could use someString.charAt() to do both. Then implement any sorting algorithm you want. Commented Aug 26, 2015 at 7:49
  • @Manu how do you propose to do shuffle without any random method? I think bubble sort is the easiest to do without methods Commented Aug 26, 2015 at 8:10

3 Answers 3

3

I will not give you any code, as this is clearly an assignment, but here's some general guidance:

  1. Don't try to put everything into main. You may not be allowed to use any exiting API, but you can define your own! Write your own compare and sort methods.
  2. Start with a method compare(String, String) -> int, or isSmaller(String, String) -> boolean. Use String.toCharArray to get the individual characters and compare them, in pairs from both strings. Make sure to handle the case of the strings having different lengths.
  3. Now write a method compare(String[], String[]) -> int. This can look very similar to the above (in fact, you could make a generic one for both), but it might be simpler to make this one specific for the "lastname-firstname" case, particularly since here you want to sort by the second element first.
  4. Finally, write your own sort method. An in-place bubble sort should be the easiest and the algorithm can easily be found on the internet. Other sort algorithms are faster, but if speed is an issue, the requirement not to use any API is nonsensical in the first place. If you want to score bonus-points, though, you can try to implement an in-place quick sort, but only after you've got it running with the bubble sort.

Also, you should test each of those methods individually. Don't try to run your sort method before you've made sure your compare methods actually work. Call them individually with different outputs and see whether they yield the correct result.

Sign up to request clarification or add additional context in comments.

Comments

1
public class NameSort {

    public static void main(String[] args) {

        String [][] names={{"Jen","Eric"},
          {"Brain","Adams"},
          {"Jon","Methew"},
          {"Antino","Ronald"},
          {"Cris","Ronald"}
         };

        for(int m=0;m<names.length;m++)
        {
            for(int n=m+1;n<names.length;n++)
            {
                if(myCompare(names[m][1],names[n][1])==1)
                {
                    swap(names, names[m], names[n], m, n);
                }
                else if (myCompare(names[m][1],names[n][1])==0)
                {
                    if(myCompare(names[m][0],names[n][0])==1)
                    {
                        swap(names, names[m], names[n], m, n);
                    }
                }
            }
        }
        for (int i=0;i<names.length;i++)
        {
            System.out.println(names[i][0]+" " +names[i][1] );
        }

    }

    public static void swap(String [][] names,String[] a,String[] b,int m,int n)
    {
        names[n]=a;
        names[m]=b;
    }

    public static int myCompare(String a, String b)
    {
        int minLength= a.length()<b.length()?a.length():b.length();
        for(int i=0;i<minLength;i++)
        {
            if(a.charAt(i)>b.charAt(i))
            {
                return 1;
            }
            else if(a.charAt(i)<b.charAt(i)){
                return -1;
            }
        }
        if(a.length()>minLength)
            return 1;
        else if (b.length()> minLength )
            return -1;
        else
            return 0;
    }
}

Comments

0

In order to let you learn at least something, I am going to give you the answer in psuedo-code and let you do the coding. The solution is based on bubble sort and comparing names (=Strings) by looping on their characters

in bubble sort we iterate over the array, in each iteration, we compare two adjacent cells and possibly swap them so that they are in the correct order. at the end of the 1st iteration, the biggest cell will be in the correct position (=last). so we start another iteration but skip the last cell. by the end of the 2nd iteration, the 2nd biggest cell will in its correct position. we cotinue iterating, each time going over one less cell until there are no more cells to iterate over.

I give you the comparing method: The solution assumes you are allowed to call length() and charAt() methods of String class.

/**
 * returns negative, zero or positive value 
 * if s1 is smaller, equal or bigger than s2, respectively
 * comparison is lexicographical
 */
static int compareStrings(String s1, String s2)
{
    int i = 0;
    for (i = 0; i < s1.length() && i < s2.length(); i++) {
        int diff = s1.charAt(i) - s2.charAt(i);
        if (diff != 0) return diff;
    }
    if (i == s1.length()) {
        if (i == s2.length()) return 0; // equal lengths
        else return 1; // exhausted s2 before s1
    }
    return -1; // exhausted s1 before s2
}

seeing the loop in your code, I think one last note is in order: you should be aware that arrays in Java start with index 0 and the last cell is at length-1.

1 Comment

show your thanks with up voting and/or accpepting, please

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.