Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 18 of 18

Thread: Sorting Strings

  1. #1
    Junior Member
    Join Date
    Feb 2012
    Posts
    24
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Question Sorting Strings

    I need to modify this movies program so that way the DVDs will be sorted by title at all times (A first thru Z). The performance of the code will be scrutinized, so I need to produce the best modifications to achieve the requirements.
    Is there a way to sort the strings by title without sorting methods? If that makes any sense.

    Thank you for your help. The 3 classes of this program are pasted below. (Movies -> DVDCollection -> DVD)

    public class Movies
    {
       //  Creates a DVDCollection object and adds some DVDs to it. Prints
       //  reports on the status of the collection.
       public static void main (String[] args)
       {
          DVDCollection movies = new DVDCollection();
    *
          movies.addDVD ("The Godfather", "Francis Ford Coppala", 1972, 24.95, true);
          movies.addDVD ("District 9", "Neill Blomkamp", 2009, 19.95, false);
          movies.addDVD ("Iron Man", "Jon Favreau", 2008, 15.95, false);
          movies.addDVD ("All About Eve", "Joseph Mankiewicz", 1950, 17.50, false);
          movies.addDVD ("The Matrix", "Andy & Lana Wachowski", 1999, 19.95, true);
    *
          System.out.println (movies);
    *
          movies.addDVD ("Iron Man 2", "Jon Favreau", 2010, 22.99, false);
          movies.addDVD ("Casablanca", "Michael Curtiz", 1942, 19.95, false);
    *
          System.out.println (movies);
       }
    }

    import java.text.NumberFormat;
    import java.util.Collections;
    public class DVDCollection
    {
       private DVD[] collection;
       private int count;
       private double totalCost;
    *
       //-----------------------------------------------------------------
       //  Constructor: Creates an initially empty collection.
       //-----------------------------------------------------------------
       public DVDCollection ()
       {
          collection = new DVD[100];
          count = 0;
          totalCost = 0.0;
       }
    *
       //  Adds a DVD to the collection, increasing the size of the
       //  collection array if necessary.
    *
       public void addDVD (String title, String director, int year, double cost, boolean bluRay)
       {
          if (count == collection.length)
             {
              increaseSize();
              }
    *
          collection[count] = new DVD (title, director, year, cost, bluRay);
          totalCost += cost;
          count++;
       }
    *
       //  Returns a report describing the DVD collection.
       public String toString()
       {
          NumberFormat fmt = NumberFormat.getCurrencyInstance();
    *
          String report = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
          report += "My DVD Collection\n\n";
    *
          report += "Number of DVDs: " + count + "\n";
          report += "Total cost: " + fmt.format(totalCost) + "\n";
          report += "Average cost: " + fmt.format(totalCost/count);
    *
          report += "\n\nDVD List:\n\n";
    *
          for (int dvd = 0; dvd < count; dvd++)
          {
              report += collection[dvd].toString() + "\n";
          }
    *
          return report;
       }
       //  Increases the capacity of the collection by creating a
       //  larger array and copying the existing collection into it.
    *
       private void increaseSize ()
       {
          DVD[] temp = new DVD[collection.length * 2];
    *
          for (int dvd = 0; dvd < collection.length; dvd++)
           {
             temp[dvd] = collection[dvd];
            }
    *
          collection = temp;
       }
    }

    import java.text.NumberFormat;
    *
    public class DVD
    {
       private String title, director;
       private int year;
       private double cost;
       private boolean bluRay;
    *
       //  Creates a new DVD with the specified information.
    *
       public DVD (String title, String director, int year, double cost, boolean bluRay)
       {
          this.title = title;
          this.director = director;
          this.year = year;
          this.cost = cost;
          this.bluRay = bluRay;
       }
    *
    *
       public String getTitle()
       {
           return title;
       }
       //  Returns a string description of this DVD.
       public String toString()
       {
          NumberFormat fmt = NumberFormat.getCurrencyInstance();
    *
          String description;
    *
          description = fmt.format(cost) + "\t" + year + "\t";
          description += title + "\t" + director;
    *
          if (bluRay)
          {
             description += "\t" + "Blu-Ray";
          }
    *
          return description;
       }
    *
    }




    It prints the following so far, unsorted:

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    My DVD Collection

    Number of DVDs: 5
    Total cost: $98.30
    Average cost: $19.66

    DVD List:

    $24.95 1972 The Godfather Francis Ford Coppala Blu-Ray
    $19.95 2009 District 9 Neill Blomkamp
    $15.95 2008 Iron Man Jon Favreau
    $17.50 1950 All About Eve Joseph Mankiewicz
    $19.95 1999 The Matrix Andy & Lana Wachowski Blu-Ray

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    My DVD Collection

    Number of DVDs: 7
    Total cost: $141.24
    Average cost: $20.18

    DVD List:

    $24.95 1972 The Godfather Francis Ford Coppala Blu-Ray
    $19.95 2009 District 9 Neill Blomkamp
    $15.95 2008 Iron Man Jon Favreau
    $17.50 1950 All About Eve Joseph Mankiewicz
    $19.95 1999 The Matrix Andy & Lana Wachowski Blu-Ray
    $22.99 2010 Iron Man 2 Jon Favreau
    $19.95 1942 Casablanca Michael Curtiz



    Should I use an algorithm to sort like this?
    public static void sort(DVD [] collection, int counter)
    {
     
    int a,b;
    String temp;
    int sortStrings = counter - 1;
    for (a = 0; a < sortStrings; ++a)
    for (b = 0; b < sortStrings; ++b)
    if(collection[b].compareTo(collection[b + 1]) >0)
    {
    temp = collection[b];
    collection[b] = collection[b + 1];
    collection[b + 1] = temp;	
    }
    }
    Last edited by userct; February 22nd, 2012 at 01:57 PM.


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Sorting Strings

    Are you familiar with sorting algorithms? If so, what did you try? Where are you stuck? Are you required to write your own? If not, the Collections.sort method might be of use. All these questions suggest you should provide a lot more information to get the help you wish.

  3. #3
    Junior Member
    Join Date
    Feb 2012
    Posts
    24
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Sorting Strings

    I'm not too familiar with sorting algorithms as we were just taught it and this was sprung on us. I don't want to go into the programming field but this class is required. I'm not sure how or what algorithm or process I should use to sort the strings by title. So as of right now I haven't tried anything, I'm just trying to figure out what I should use and how I can go about sorting these strings.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Sorting Strings

    Should I use an algorithm to sort like this?
    Does it do the sorting you want? If so, use it.

    Please Edit your post and wrap your code with[code=java]<YOUR CODE HERE>[/code] to get highlighting

  5. #5
    Junior Member
    Join Date
    Feb 2012
    Posts
    24
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Sorting Strings

    I'm not sure if it sorts how I want it because I'm not sure exactly how to incorporate it in my code.
    Sorry if anything I say sounds incorrect, I'm relatively new to this.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Sorting Strings

    For testing, create a small program with a small array of DVD objects, print out the array, call the sort method and then print out the array after the sort.
    That should allow you to test the sorting method and see how to use it.

  7. #7
    Junior Member
    Join Date
    Feb 2012
    Posts
    24
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Sorting Strings

    I actually was told today that I have to use Binary Search in order to sort the strings.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Sorting Strings

    Have you looked up/Googled the logic for a Binary search?

  9. #9
    Junior Member
    Join Date
    Feb 2012
    Posts
    24
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Sorting Strings

    I've looked briefly. I'm looking at it more now, thank you.

  10. #10
    Junior Member
    Join Date
    Feb 2012
    Posts
    24
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Sorting Strings

    I looked at some code and made a structure below. I'm not on my programming computer so I just wrote and examined binary search. I believe this should work. I was wondering if I can call this in my DVDCollection class or do I need to create a new class?

    BINARY SEARCH METHOD EXAMPLE: (Better than linear)
    ** public static Comparable binarySearch (Comparable[] list, Comparable target)
    ** {
    ***** int min=0, max=list.length-1, mid=0;
    ***** boolean found = false;
    ***** while (!found && min <= max)
    ***** {
    ******** mid = (min+max) / 2;
    ******** if (list[mid].compareTo(target) == 0)
    *********** found = true;
    ******** else
    *********** if (target.compareTo(list[mid]) < 0)
    ************** max = mid-1;
    *********** else
    ************** min = mid+1;
    ***** }
    ***** if (found)
    ******** return list[mid];
    ***** else
    ******** return null;
    ** }

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Sorting Strings

    Putting it in its own class would let you use it in other apps.

  12. #12
    Junior Member
    Join Date
    Feb 2012
    Posts
    24
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Sorting Strings

    Since I only Need it for this one and have to modify the current code I actually should probaby put it in one of the current classes. Thank you.

  13. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Sorting Strings

    However you want to do it.

  14. #14
    Member
    Join Date
    Feb 2012
    Posts
    106
    My Mood
    Yeehaw
    Thanks
    8
    Thanked 11 Times in 11 Posts

    Default Re: Sorting Strings

    the first time using binary search (or any new search routine) you should do rigorous testing to make sure it behaves exactly how you want it. 20 print lines is common. sometimes it helps to use JOptionPane so you can control the speed the program iterates, and follow along on paper. it is especially important to check the ends and center with binary search. also just to be sure, remember with any search, your data has to be organized in a predictable manner (usually low to high or high to low) for a more complex search to work. GL!

  15. #15
    Junior Member
    Join Date
    Feb 2012
    Posts
    24
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Sorting Strings

    With that binary search method how do I get it to run the dvds through it?
    As it is structured now it uses Comparable [] list. Do I need to somehow put the DVDs in that list or put DVDCollection in its place? How could I correctly implement it?
    -Thank you all for your input and help.

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Sorting Strings

    If the items to be sorted are in an array and the method takes an array as a parameter, have you tried calling the method with the array as an argument?

  17. #17
    Junior Member
    Join Date
    Feb 2012
    Posts
    24
    My Mood
    Confused
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Sorting Strings

    No I haven't. I undertand the logic behind it but always have trouble putting it correctly into code.

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Sorting Strings

    do it in small steps:
    Put the items to be sorted into a list.
    Print out the contents of the list to see the BEFORE order.
    Adding a toString() method to the class will make it easier to print out the list's contents.

Similar Threads

  1. [SOLVED] Sorting strings alphabetically
    By userct in forum What's Wrong With My Code?
    Replies: 0
    Last Post: February 21st, 2012, 04:38 PM
  2. Sorting a Arraylist
    By waterjames in forum Java Theory & Questions
    Replies: 1
    Last Post: November 26th, 2010, 02:47 PM
  3. [SOLVED] Method of Sorting? by assiging numerical values to Strings
    By Mirage in forum Java Theory & Questions
    Replies: 0
    Last Post: June 16th, 2010, 07:49 PM
  4. Sorting an Array
    By Prince_85 in forum Algorithms & Recursion
    Replies: 2
    Last Post: February 21st, 2010, 03:00 PM
  5. [SOLVED] sorting
    By kite98765 in forum Algorithms & Recursion
    Replies: 8
    Last Post: February 4th, 2010, 08:34 AM