Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.
Hi all, please see this major site announcement: https://www.boards.ie/discussion/2058427594/boards-ie-2026

sorting an algorithm

  • 28-03-2008 03: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, Registered Users 2 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, Registered Users 2 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
Advertisement