Results 1 to 11 of 11
  1. #1
    Beginner's Avatar
    Beginner is offline Member
    Join Date
    Apr 2010
    Posts
    25
    Rep Power
    0

    Default Code seems to be correct, but why does it sometimes go wrong?

    Hello, I'm tying to create a sorter, for words, which will supposedly sort them alphabetically. Tried different words on it. It sometimes sorts them correctly, but sometimes it gives the wrong answer. I reviewed my code countless times already and I can't seem to figure out what's wrong, it even compiles ok and does not give any runtime errors, it just gives a wrong answer.

    BTW: I'm trying to do a bubble sort on it

    Java Code:
    import java.util.Scanner;
    
    public class Alphabetical {
    
    	public static void main(String[] args) {
    		//Get the unsorted words from input
    		Scanner myScanner = new Scanner(System.in);
    		System.out.println("Please enter words:");
    		String unSorted = myScanner.nextLine();
    		
    		//Find out how long should the length of the array be
    		int length = 0;
    		Scanner lengthScanner = new Scanner(unSorted);
    		do {
    			lengthScanner.next();
    			length++;
    		} while(lengthScanner.hasNext());
    		
    		//Load all the words into a new String array, also converts to lower case
    		String words[] = new String[length];		
    		Scanner lineScanner = new Scanner(unSorted);
    		for(int loader = 0; loader < length; loader++ ) {
    			words[loader] = lineScanner.next().toLowerCase();
    		}
    		
    		//Sort the words
    		for(int i=0; i < length; i++) {
    			for(int j=0; j < length-1; j++) {
    				//Test which word is shorter, use shorter word length
    				int wordLength = words[j].length() > words[j+1].length() ? words[j+1].length() : words[j].length();
    				
    				//Switch the two words if 2nd word precedes the 1st word
    				boolean precedes = false;
    				for(int k=0; k < wordLength; k++) {
    					if(words[j].charAt(k) > words[j+1].charAt(k)) {
    						precedes = true;
    					}
    				}
    				
    				if(precedes) {
    					String temp;
    					temp = words[j];
    					words[j] = words[j+1];
    					words[j+1] = temp;
    				}
    			}
    		}
    		
    		//Display the newly sorted words
    		for(int count = 0; count < length; count++) {
    			System.out.print(words[count] + " ");
    		}
    	}
    }

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,765
    Blog Entries
    7
    Rep Power
    21

    Default

    Why reinvent the wheel when it already has been done before? You don't need all that code; study this:

    Java Code:
    import java.util.Arrays;
    
    public class T {
    	public static void main(String[] args) {
    
    	String line= "Foo bar BAZZ"; // words to be sorted
    	String[] words= line.split("\\s+"); // separate words in an array
    	
    	Arrays.sort(words, String.CASE_INSENSITIVE_ORDER); // sort them
    	
    	System.out.println(Arrays.toString(words)); // print them
    	}
    }
    kind regards,

    Jos

  3. #3
    Beginner's Avatar
    Beginner is offline Member
    Join Date
    Apr 2010
    Posts
    25
    Rep Power
    0

    Default

    JosAH: Thanks! Never knew the Arrays.sort() method could also work on words.

    But anyway I'm still really curious as to where I made a mistake, anyone noticed something?

  4. #4
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,765
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Beginner View Post
    JosAH: Thanks! Never knew the Arrays.sort() method could also work on words.

    But anyway I'm still really curious as to where I made a mistake, anyone noticed something?
    Can you give us a (small) example for which your sorting implementation doesn't work? b.t.w. that is a very inefficient sorting algorithm, Arrays.sort( ... ) does a much better job ...

    kind regards,

    Jos

  5. #5
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,765
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Beginner View Post
    But anyway I'm still really curious as to where I made a mistake, anyone noticed something?
    Found if: suppose you're sorting the words "foox" and "foo" in that order; you only compare three character and decide that they need not to be swapped.

    kind regards,

    Jos

  6. #6
    Beginner's Avatar
    Beginner is offline Member
    Join Date
    Apr 2010
    Posts
    25
    Rep Power
    0

    Default

    Try the words "angel" "banana" "dove" in that order, and even though it's already sorted, it sorts angel and banana

    BTW: I looked for your example in the API, and why can't I find a sort() method with the parameters of a String array?

    http://java.sun.com/javase/6/docs/ap...il/Arrays.html
    Last edited by Beginner; 06-06-2010 at 10:36 AM.

  7. #7
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,765
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Beginner View Post
    Try the words "angel" "banana" "dove" in that order, and even though it's already sorted, it sorts angel and banana
    (also read my previous reply); your comparison loop is dead wrong: first it checks the 'a' (from 'angel') and the 'b' (from 'banana') and decides not to set that boolean variable to true; the next pass of the loop it checks the 'n' (second letter in 'angel') with 'a' (second letter in 'banana') and it (incorrectly) sets that boolean variable to true so it swaps those two words after your comparison loop has finished (the boolean variable was set to true).

    kind regards,

    Jos

  8. #8
    Beginner's Avatar
    Beginner is offline Member
    Join Date
    Apr 2010
    Posts
    25
    Rep Power
    0

    Default

    Thank you JosAH, I kinda get it now, thanks! But pls answer my question regarding the API, because Im positive I don't see a sort(String[] a) method in the API

  9. #9
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,765
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Beginner View Post
    Thank you JosAH, I kinda get it now, thanks! But pls answer my question regarding the API, because Im positive I don't see a sort(String[] a) method in the API
    There are two sort( ... ) methods in the Arrays class that can apply: one is the Arrays.sort(Object[] o) method where the Object[] array needs to contain Objects that implement the Comparable interface; the other method (the one I used in my example) takes any kind of objects T and a Comparator that can compare them (I used a pre-cooked Comparator from the String class for that purpose).

    kind regards,

    Jos

  10. #10
    Beginner's Avatar
    Beginner is offline Member
    Join Date
    Apr 2010
    Posts
    25
    Rep Power
    0

    Default

    Thank you, JosAH!

  11. #11
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,765
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Beginner View Post
    Thank you, JosAH!
    You're welcome of course; next time better use the implemented sort( ... ) method(s) and don't try to implement your own; there are so many nitty-gritty details to get right ...

    kind regards,

    Jos

Similar Threads

  1. What is wrong with my code?!
    By new2java2009 in forum New To Java
    Replies: 2
    Last Post: 04-17-2010, 09:01 PM
  2. Replies: 1
    Last Post: 10-24-2009, 03:13 AM
  3. how to mark as Correct or Wrong ?!
    By pinkdreammsss in forum New To Java
    Replies: 20
    Last Post: 05-21-2009, 11:52 AM
  4. What's wrong with this code?
    By Doctor Cactus in forum New To Java
    Replies: 4
    Last Post: 11-29-2008, 06:44 PM
  5. What's wrong with this code?
    By Wizard wusa in forum New To Java
    Replies: 14
    Last Post: 01-23-2008, 12:55 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •