1 2 Previous Next 17 Replies Latest reply: May 15, 2007 2:39 PM by 807600 RSS

    Sorting strings held in an array

    807600
      I am a bit of a newbie to java programming and I am completely stuck on this.

      For an assignment I have been asked to sort a set of arrays into alphabetical order, firstly by the surname and then by the first name. The problem is i can not use the array.sort() method(s) from the base Java class-libraries. I know how to sort an array consisting of integers, but I just can not figure out how to change my integer sorting solution into string sorting.

      My array contains:

      lastName
      firstName
      telNumber
      emailAddress

      Am I thinking in the right area thinking my original integer sorting solution can be altered in some way to achieve what I need?
        • 1. Re: Sorting strings held in an array
          807600
          i have a solution, but it may be somewhat larger one.

          First u calculate the length of the array by arr.length() func , then use a for loop to loop thru the array & get the first element of each array element by arr[0].charAt(0)... BY doung this get the ascii count & compare ecah letter with another & sort them.

          And if u need this sorting by the last name just repeat the same process by getting the char at that position
          • 2. Re: Sorting strings held in an array
            807600
            My array contains:

            lastName
            firstName
            telNumber
            emailAddress
            So I take it that these are all Strings. Are they held together in a single class, and are trying to sort objects of this class? If so, does the class implement the Comparable interface? If not, I'd implement this interface and create a compareTo method that tells Arrays.sort how to sort the objects.

            I think another method is to use a helper class that implements Comparator. This method may allow multiple different ways to sort objects of a class.

            I recommend you have a look at both these things in the javadocs.

            Good luck!

            /Pete

            Message was edited by:
            petes1234
            • 3. Re: Sorting strings held in an array
              807600
              This is how they are held:

              private static String lastName[] = new String[MAX_RECORDS];
              private static String firstName[] = new String[MAX_RECORDS];
              private static String telNumber[] = new String[MAX_RECORDS];
              private static String emailAddress[] = new String[MAX_RECORDS];

              Is this what you mean?
              • 4. Re: Sorting strings held in an array
                807600
                Bad code smell: parallel arrays.

                http://en.wikipedia.org/wiki/Code_smell
                • 5. Re: Sorting strings held in an array
                  807600
                  The array setup I just posted was given to me by my tutor, why is it a code smell?
                  • 6. Re: Sorting strings held in an array
                    807600
                    The problem is i
                    can not use the array.sort() method(s) from the base
                    Java class-libraries.
                    Do you mean your having trouble getting that to work, or that approach was explicitly forbidden for the assignment?
                    Am I thinking in the right area thinking my original
                    integer sorting solution can be altered in some way
                    to achieve what I need?
                    Yes. You didn't show code, but your solution needed an input array and an output array (both of which you still have in the string sorting problem), and at some point you needed to compare two integers (here you still need to compare two Strings). All you would need to do is replace each occurence of "int" (or perhaps you used "Integer") with "String", and replace the comparison operator with something appropriate for Strings.
                    My array contains:

                    lastName
                    firstName
                    telNumber
                    emailAddress
                    Here's the catch though. Did you declare:
                    - 1 String[] with all this information
                    - 4 String[] with this information
                    - 1 Person[], where Person is a class that has these four fields

                    Your confusion with how to apply the int sorting code to the string sorting code may start with a flaw in the data representation.

                    Also, ask yourself:
                    What is the requirements for sorting? Do the current 4 first elements all need to end up in the same index as each other? If so, perhaps going with the Person array would be better. If you just need to sort each of the arrays independently, then use 4 String arrays.
                    • 7. Re: Sorting strings held in an array
                      807600
                      The array setup I just posted was given to me by my tutor, why is it a code smell?
                      Here's a second change to click on that link: http://en.wikipedia.org/wiki/Code_smell
                      • 8. Re: Sorting strings held in an array
                        807600
                        Here's a second change to click on that link:
                        http://en.wikipedia.org/wiki/Code_smell
                        The link doesn't mention anything about parallel arrays. He could have clicked on it and still be genuinely unsure of it's relevance.

                        And in the admittedly unlikely case that the four arrays need to be sorted independently of one another, then the code smells great.
                        • 9. Re: Sorting strings held in an array
                          807600
                          And in the admittedly unlikely case that the four arrays need to be sorted independently of one another, then the code smells great.
                          Yeah, and I like durian.
                          • 10. Re: Sorting strings held in an array
                            807600
                            Thanks for your help, the array.sort method has been forbidden in my assignment.

                            You say I need to replace the comparison operator with something appropriate for Strings. What operator could I use?

                            Here is the code I used to sort integers:

                            public static void sort_students()
                                 {
                                      // Declare and Initialise Variables
                                      int temp1;
                                      String temp2;
                                      double temp3;
                                      
                                      // Sort the student arrays
                                      for (int j=0; j<no_of_students; j++)
                                           {
                                                for (int k=j+1; k<=no_of_students; k++)
                                                {
                                                     if (overall_mean[j] < overall_mean[k])
                                                     {
                                                          // Swap students information
                                                          temp1 = person_id[j];
                                                          person_id[j] = person_id[k];
                                                          person_id[k] = temp1;
                                                          
                                                          temp2 = firstname[j];
                                                          firstname[j] = firstname[k];
                                                          firstname[k] = temp2;
                                                          
                                                          temp2 = surname[j];
                                                          surname[j] = surname[k];
                                                          surname[k] = temp2;
                                                          
                                                          temp3 = overall_mean[j];
                                                          overall_mean[j] = overall_mean[k];
                                                          overall_mean[k] = temp3;
                                                     }
                                                }
                                           }
                                           
                                                     
                                 }

                            I dont quite understand what you mean by how did i declare them.

                            Once sorted they all need to end up in the same index, the lastName, firstName, telNumber and emailAddress are all linked to one person.

                            Message was edited by:
                            casinoroyale007
                            • 11. Re: Sorting strings held in an array
                              807600
                              Once sorted they all need to end up in the same
                              index, the lastName, firstName, telNumber and
                              emailAddress are all linked to one person.
                              This is where that bad smell comes in. Sorting 4 related arrays is tricky. Wouldn't you rather sort a single array? Notice how you are using the same swap technique for each of the arrays, might as well refactor the common code so that it is less prone to bugs and easier to add a new attribute to the student.

                              Such as (modifying your code only if necessary):
                              public static void sort_students() {
                                  // Declare and Initialise Variables
                                  Student temp1; //NOTE: changed type of temp1
                                  String temp2;
                                  double temp3;
                              
                                  // Sort the student arrays 
                                  //NOTE: replaced the 4 arrays with a single array, 
                                  //             declared globally as Student[] students,
                                  //             where Student has fields overallMean, personId, firstname, surname
                                  for (int j=0; j<no_of_students; j++) {
                                      for (int k=j+1; k><=no_of_students; k++) {
                                          if (students[j].getOverallMean() < students[k].getOverallMean()) {
                                              // Swap students information
                                              temp1 = students[j];
                                              students[j] = students[k];
                                              students[k] = temp1;
                                          }
                                      }
                                  }
                              }
                              This is much easier. And you can use almost the same code for the "string sorting" problem. Just change the condition in the if clause.
                              • 12. Re: Sorting strings held in an array
                                807600
                                This is where that bad smell comes in.
                                I don't know if its the four parallel arrays that smell bad or the smell of "class denial". Person class? We don't need no stinkin' Person class ;-)
                                • 13. Re: Sorting strings held in an array
                                  807600
                                  And if you haven't learned classes yet, and all you wanted from us is how to sort by the criterion of <surname,firstname>, then the changes are even simpler.

                                  Just change the predicate of the if statement. Replace the line "if (overall_mean[j] < overall_mean[k]) {" with what you need.

                                  You need to look at the API of String to see if it has any useful methods for "compare"-ing (second hint: someone already mentioned the method): http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html

                                  Message was edited by:
                                  bheilers

                                  why is i-n-g bleeped out?
                                  • 14. Re: Sorting strings held in an array
                                    807600
                                    Okay, that is not the way I was taught but it seems easier. So now if I wanted to sort strings what comparison operator would I be able to use?

                                    Thanks for your help so far
                                    1 2 Previous Next