Skip to content
Advertisement

Determine the Object (book) that appears first alphabetically

I was tasked with creating my own linked list class, using a book class i made. One of the questions was to Determine the book that appears first alphabetically.

i was able to sort the Linked list alphabetically using bubble sort(i know its not efficient but im still new) here is the code.

public void alphaBubbleSort() {
    int size = size();

    if (size > 1) {
        boolean wasChanged;

        do {
            Node current = head;
            Node previous = null;
            Node next = head.next;
            wasChanged = false;
            while (next != null) {
                if (current.book.getName().compareToIgnoreCase(next.book.getName()) > 0) {

                    wasChanged = true;

                    if (previous != null) {
                        Node sig = next.next;

                        previous.next = next;
                        next.next = current;
                        current.next = sig;
                    } else {
                        Node temp = next.next;

                        head = next;
                        next.next = current;
                        current.next = temp;
                    }

                    previous = next;
                    next = current.next;
                } else {
                    previous = current;
                    current = next;
                    next = next.next;
                }
            }
        } while (wasChanged);
    }
}

my problem is i only want the front node and i do not want to alter the linked list order. i tried to do this in my main.

Linky tempLinky = new Linky(); // create temp linked list
           tempLinky = linky; // copy temp main linked list to temp
           tempLinky.alphaBubbleSort(); // sort temp list
           System.out.println(tempLinky.peek());// return object in first node

This did not seem to work. Ive tried some other code that does not work, so ive come here as a last resort.

Advertisement

Answer

If you need to find the first book alphabetically, there’s no need to sort the entire list (and, as you commented, you don’t want to alter the list’s order anyway).

Instead, you could iterate over the list and keep the “first” object as you go:

public Book getFirstAlphabetically() {
     Node current = head;
     Book retVal = head.book;
     while (current != null) {
         if (current.book.getName().compareToIgnoreCase(retVal.getName()) < 0) {
             retVal = current.book;
         }
         current = current.next;
     }
     return retVal;
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement