Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

sorting an algorithm

Options
  • 28-03-2008 3:50am
    #1
    Closed Accounts Posts: 20


    how do i sort this by name.


    if (option.equals("2")) {
    System.out.println("Display PhoneBook");
    System.out.println("
    ");
    System.out.println("Name" + " Number");
    for (int i = 0; i < currentPos; i++) {
    System.out.println(phonebook.getName() + " " + phonebook.getNumber());
    }
    System.out.println("

    ");
    }
    this section of code is to display all information,i just have to sort it in alphabetical order


Comments

  • Registered Users Posts: 1,922 ✭✭✭fergalr


    Inferring from your example code that you have a Phonebook class, instances of which live in the phonebook[] array, the best thing to do is probably make the Phonebook class implement the comparator interface.
    See here:
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/Comparator.html
    for details. It's not near as bad as it first looks, it's only really a compare method, google the comparator interface if you have difficulty.

    Then, you probably want to use the Arrays.sort method to sort your phonebook array using a comparator.
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/Arrays.html#sort(java.lang.Object[])

    Shouldn't take you too long, and is probably be best java way of solving the problem.


  • Registered Users Posts: 7,468 ✭✭✭Evil Phil


    Sorting an algorithm is basic CS101 stuff. If you're unable to do your homework heavy482 perhaps you should consider another course. I've warned you about this before.

    Thread locked.


This discussion has been closed.
Advertisement