Skip to content

Commit 1cf6847

Browse files
author
Alex Klymenko
committed
Fix Swap Sort Implementation: Correct Logic and Improve Efficiency
1 parent 308bdcf commit 1cf6847

File tree

2 files changed

+20
-51
lines changed

2 files changed

+20
-51
lines changed

src/main/java/com/thealgorithms/sorts/SwapSort.java

Lines changed: 12 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -9,64 +9,25 @@
99
*/
1010
public class SwapSort implements SortAlgorithm {
1111

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+
*/
1219
@Override
1320
public <T extends Comparable<T>> T[] sort(T[] array) {
1421
int len = array.length;
15-
int index = 0;
1622

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+
}
2428
}
2529
}
2630

2731
return array;
2832
}
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-
}
7233
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package com.thealgorithms.sorts;
2+
3+
public class SwapSortTest extends SortingAlgorithmTest {
4+
@Override
5+
SortAlgorithm getSortAlgorithm() {
6+
return new SwapSort();
7+
}
8+
}

0 commit comments

Comments
 (0)