String Alphabetising

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Beje
    New Member
    • Jul 2006
    • 1

    #1

    String Alphabetising

    Greetings all,

    I am new to the java programming language. I seem to have hit the wall when I try to sort words a user inputs.

    I am trying to sort like four input words from the user and then alphabetise them...

    I used the s.compareTo(t) method but the way I did it ended up being much longer then I tought... I must be overlooking something...( I compared each of the words to each other individually )

    I am thinking that I could maybe use a loop with the if statement to help me sort with the compareTo method but I am stuck sigh :(.

    Any help or pointers to the right dirrection on this would be much appreciated
  • D_C
    Contributor
    • Jun 2006
    • 293

    #2
    There are all types of different sorting algorithms, it is a very big topic, especially for beginners. It sounds like may have done bubble sort, the simplest, but least efficient one.

    I think merge sort is the best in terms of run time and least confusing. Quick sort is a little better in practice, but difficult to explain. If you know you will only have four variables, you could type it out, but the recursion of merge sort is very nice.

    Suppose you have four variables:
    a b c d

    compare a and b, swap them if b is smaller.
    similarly, compare c and d. Suppose b < a, c < d, then we have two sorted lists:
    b a
    c d

    Then just merge them together, i.e. merge sort. Compare b to c, suppose c < b.
    Know we know that c is the minimum since c < d, and c < b < a.
    c b a
    d

    We just need to know where d goes. We already know c < d, so we compare b to d. This comparison determines the next smaller number. Suppose b < d. It doesn't help us in placing d, but we know where b goes now, since c < b < a and c < b < d

    Finally we have to compare d and a. Suppose d < a. Now we can have a sorted list because we know how everything ranks, c < b < d < a, so:
    c b d a

    You should always need five comparisons, if you are going to implement merge sort non-recursively, for four elements. I recommend you check out Google, there are plenty of merge sort, and other sort algorithm implementations :D.

    Comment

    Working...