|
| 1 | +package Sorts; |
| 2 | + |
| 3 | +import static Sorts.SortUtils.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * The idea of Swap-Sort is to count the number m of smaller values (that are in |
| 7 | + * A) from each element of an array A(1...n) and then swap the element with the |
| 8 | + * element in A(m+1). This ensures that the exchanged element is already in the |
| 9 | + * correct, i.e. final, position. The disadvantage of this algorithm is that |
| 10 | + * each element may only occur once, otherwise there is no termination. |
| 11 | + */ |
| 12 | +public class SwapSort implements SortAlgorithm { |
| 13 | + |
| 14 | + @Override |
| 15 | + public <T extends Comparable<T>> T[] sort(T[] array) { |
| 16 | + int LENGTH = array.length; |
| 17 | + int index = 0; |
| 18 | + |
| 19 | + while (index < LENGTH - 1) { |
| 20 | + int amountSmallerElements = this.getSmallerElementCount(array, index); |
| 21 | + |
| 22 | + if (amountSmallerElements > 0 && index != amountSmallerElements) { |
| 23 | + T element = array[index]; |
| 24 | + array[index] = array[amountSmallerElements]; |
| 25 | + array[amountSmallerElements] = element; |
| 26 | + } else { |
| 27 | + index++; |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + return array; |
| 32 | + } |
| 33 | + |
| 34 | + private <T extends Comparable<T>> int getSmallerElementCount(T[] array, int index) { |
| 35 | + int counter = 0; |
| 36 | + for (int i = 0; i < array.length; i++) { |
| 37 | + if (less(array[i], array[index])) { |
| 38 | + counter++; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + return counter; |
| 43 | + } |
| 44 | + |
| 45 | + public static void main(String[] args) { |
| 46 | + // ==== Int ======= |
| 47 | + Integer[] a = { 3, 7, 45, 1, 33, 5, 2, 9 }; |
| 48 | + System.out.print("unsorted: "); |
| 49 | + print(a); |
| 50 | + System.out.println(); |
| 51 | + |
| 52 | + new SwapSort().sort(a); |
| 53 | + System.out.print("sorted: "); |
| 54 | + print(a); |
| 55 | + System.out.println(); |
| 56 | + |
| 57 | + // ==== String ======= |
| 58 | + String[] b = { "banana", "berry", "orange", "grape", "peach", "cherry", "apple", "pineapple" }; |
| 59 | + System.out.print("unsorted: "); |
| 60 | + print(b); |
| 61 | + System.out.println(); |
| 62 | + |
| 63 | + new SwapSort().sort(b); |
| 64 | + System.out.print("sorted: "); |
| 65 | + print(b); |
| 66 | + } |
| 67 | +} |
0 commit comments