Skip to content

Commit a5b4c61

Browse files
alxkmvil02
andauthored
fix: avoid infinite loop in SwapSort (#5248)
--------- Co-authored-by: vil02 <[email protected]>
1 parent 308bdcf commit a5b4c61

File tree

2 files changed

+11
-35
lines changed

2 files changed

+11
-35
lines changed

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

+3-35
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ public <T extends Comparable<T>> T[] sort(T[] array) {
1717
while (index < len - 1) {
1818
int amountSmallerElements = this.getSmallerElementCount(array, index);
1919

20-
if (amountSmallerElements > 0 && index != amountSmallerElements) {
21-
SortUtils.swap(array, index, amountSmallerElements);
20+
if (amountSmallerElements > 0) {
21+
SortUtils.swap(array, index, index + amountSmallerElements);
2222
} else {
2323
index++;
2424
}
@@ -29,44 +29,12 @@ public <T extends Comparable<T>> T[] sort(T[] array) {
2929

3030
private <T extends Comparable<T>> int getSmallerElementCount(T[] array, int index) {
3131
int counter = 0;
32-
for (int i = 0; i < array.length; i++) {
32+
for (int i = index + 1; i < array.length; i++) {
3333
if (SortUtils.less(array[i], array[index])) {
3434
counter++;
3535
}
3636
}
3737

3838
return counter;
3939
}
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-
}
7240
}
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)