Results 1 to 3 of 3

Thread: Die Bubblesort

  1. #1
    N3VRMND is offline Member
    Join Date
    Oct 2009
    Posts
    3
    Rep Power
    0

    Default Die Bubblesort

    OK so I have to make this program where it takes input (names) from the user. The names are strings of course. The names are entered into an array where a bubblesort method dealy then sorts them alphabetically. I have it so that It will takes names from the user and puts them in an array but I have not the slightest clue on how to sort them. I have some sort of pseudo code kind of deal going on at the bottom.
    import java.util.Scanner;

    Java Code:
    public class NameList
    {
    
        public static void main(String[] args)
        {
            Scanner scan = new Scanner(System.in);
            int listLength, index = 0;
            String[] nameList;
            String nameIndex;
    
            System.out.print("How many names? ");
            listLength = scan.nextInt() + 1;
            nameList = new String[listLength];
    
            while (index < listLength)
            {
                nameIndex = scan.nextLine();
                nameList[index] = nameIndex;
    
                System.out.print("=> ");
                index++;
            }
    
            for (int k = nameList.length - 2; k > 1; k--)
            {
                for (int j = k; nameList[j] < nameList[j + 1]; j++)
                {
                    swap(nameList[j], nameList[j + 1]);
                }
            }
        }
    }

  2. #2
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    You can't use < for comparing strings. Use the compareTo method.
    Then you obviously also need to implement that swap method (that should be simple enough).
    Also make sure to understand the algorithm.

  3. #3
    N3VRMND is offline Member
    Join Date
    Oct 2009
    Posts
    3
    Rep Power
    0

    Default

    Thanks but I ended up just using

    Arrays.sort(nameList);

    Does the same thing. Screw bubblesort;

Posting Permissions

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