|
9 | 9 | */
|
10 | 10 | public class SwapSort implements SortAlgorithm {
|
11 | 11 |
|
| 12 | + /** |
| 13 | + * Sorts the input array using the swap sort algorithm. |
| 14 | + * |
| 15 | + * @param array the array to be sorted |
| 16 | + * @param <T> the type of elements in the array, which must be Comparable |
| 17 | + * @return the sorted array |
| 18 | + */ |
12 | 19 | @Override
|
13 | 20 | public <T extends Comparable<T>> T[] sort(T[] array) {
|
14 | 21 | int len = array.length;
|
15 |
| - int index = 0; |
16 | 22 |
|
17 |
| - while (index < len - 1) { |
18 |
| - int amountSmallerElements = this.getSmallerElementCount(array, index); |
19 |
| - |
20 |
| - if (amountSmallerElements > 0 && index != amountSmallerElements) { |
21 |
| - SortUtils.swap(array, index, amountSmallerElements); |
22 |
| - } else { |
23 |
| - index++; |
| 23 | + for (int i = 0; i < len - 1; i++) { |
| 24 | + for (int j = i + 1; j < len; j++) { |
| 25 | + if (SortUtils.less(array[j], array[i])) { |
| 26 | + SortUtils.swap(array, i, j); |
| 27 | + } |
24 | 28 | }
|
25 | 29 | }
|
26 | 30 |
|
27 | 31 | return array;
|
28 | 32 | }
|
29 |
| - |
30 |
| - private <T extends Comparable<T>> int getSmallerElementCount(T[] array, int index) { |
31 |
| - int counter = 0; |
32 |
| - for (int i = 0; i < array.length; i++) { |
33 |
| - if (SortUtils.less(array[i], array[index])) { |
34 |
| - counter++; |
35 |
| - } |
36 |
| - } |
37 |
| - |
38 |
| - return counter; |
39 |
| - } |
40 |
| - |
41 |
| - public static void main(String[] args) { |
42 |
| - // ==== Int ======= |
43 |
| - Integer[] a = {3, 7, 45, 1, 33, 5, 2, 9}; |
44 |
| - System.out.print("unsorted: "); |
45 |
| - SortUtils.print(a); |
46 |
| - System.out.println(); |
47 |
| - |
48 |
| - new SwapSort().sort(a); |
49 |
| - System.out.print("sorted: "); |
50 |
| - SortUtils.print(a); |
51 |
| - System.out.println(); |
52 |
| - |
53 |
| - // ==== String ======= |
54 |
| - String[] b = { |
55 |
| - "banana", |
56 |
| - "berry", |
57 |
| - "orange", |
58 |
| - "grape", |
59 |
| - "peach", |
60 |
| - "cherry", |
61 |
| - "apple", |
62 |
| - "pineapple", |
63 |
| - }; |
64 |
| - System.out.print("unsorted: "); |
65 |
| - SortUtils.print(b); |
66 |
| - System.out.println(); |
67 |
| - |
68 |
| - new SwapSort().sort(b); |
69 |
| - System.out.print("sorted: "); |
70 |
| - SortUtils.print(b); |
71 |
| - } |
72 | 33 | }
|
0 commit comments