Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Selection Sort Algorithm

807603Nov 6 2007 — edited Nov 6 2007
I'm trying to implement a selection sort method with linked lists, but I just can't seem to get it to work correctly.
 public void selectionSort(LinkedList list) {
        int iterationsINNER = 1, iterationsOUTER = 1, swaps = 0, comparisons = 1;
        if(list.isEmpty())
            System.out.println("List is currently empty.");
        else if (list.size() == 1)
            System.out.println("List is already sorted.");
        else {
            Node pointer = list.getFirst();
            Node current;
            boolean exchangeMade;
            while (pointer.getNext() != null) {
                current = pointer;
                exchangeMade = false;
                iterationsOUTER++;
                while (current.getNext() != null && !exchangeMade) {
                    if(current.getNext().getData() < current.getData()) {
                        int temp = current.getData();
                        pointer.setData(current.getNext().getData());
                        current.getNext().setData(temp);
                        exchangeMade = true;
                        iterationsINNER++;
                        swaps++;
                        comparisons++;
                    }
                    current = current.getNext();
                }
                pointer = pointer.getNext();
            }
          //  System.out.println("Comparisons: " + comparisons + " \nSwaps: " + swaps + " \nIterations: " + iterationsINNER+iterationsOUTER);
        }
    }
If I test it with this code...
        LinkedList list = new LinkedList();
        list.insert(5);
        list.insert(29);
        list.insert(2);
        list.insert(1);
        list.insert(13);
        list.insert(8);
        list.insert(30);
        list.insert(3);
        sort.selectionSort(list);
        list.print();
I get this as my output...
8
13
1
2
29
5
30
30
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 4 2007
Added on Nov 6 2007
9 comments
531 views