# Selection Sort Algorithm

**807603**Nov 6, 2007 8:28 PM

I'm trying to implement a selection sort method with linked lists, but I just can't seem to get it to work correctly.

8

13

1

2

29

5

30

30

```
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

- 46 Views
- Tags: none (add)