fix: avoid infinite loop in SwapSort (#5248)

---------

Co-authored-by: vil02 <65706193+vil02@users.noreply.github.com>
This commit is contained in:
Alex Klymenko
2024-06-24 09:49:01 +03:00
committed by GitHub
parent 308bdcfc19
commit a5b4c6173f
2 changed files with 11 additions and 35 deletions

View File

@ -17,8 +17,8 @@ public class SwapSort implements SortAlgorithm {
while (index < len - 1) {
int amountSmallerElements = this.getSmallerElementCount(array, index);
if (amountSmallerElements > 0 && index != amountSmallerElements) {
SortUtils.swap(array, index, amountSmallerElements);
if (amountSmallerElements > 0) {
SortUtils.swap(array, index, index + amountSmallerElements);
} else {
index++;
}
@ -29,7 +29,7 @@ public class SwapSort implements SortAlgorithm {
private <T extends Comparable<T>> int getSmallerElementCount(T[] array, int index) {
int counter = 0;
for (int i = 0; i < array.length; i++) {
for (int i = index + 1; i < array.length; i++) {
if (SortUtils.less(array[i], array[index])) {
counter++;
}
@ -37,36 +37,4 @@ public class SwapSort implements SortAlgorithm {
return counter;
}
public static void main(String[] args) {
// ==== Int =======
Integer[] a = {3, 7, 45, 1, 33, 5, 2, 9};
System.out.print("unsorted: ");
SortUtils.print(a);
System.out.println();
new SwapSort().sort(a);
System.out.print("sorted: ");
SortUtils.print(a);
System.out.println();
// ==== String =======
String[] b = {
"banana",
"berry",
"orange",
"grape",
"peach",
"cherry",
"apple",
"pineapple",
};
System.out.print("unsorted: ");
SortUtils.print(b);
System.out.println();
new SwapSort().sort(b);
System.out.print("sorted: ");
SortUtils.print(b);
}
}

View File

@ -0,0 +1,8 @@
package com.thealgorithms.sorts;
public class SwapSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new SwapSort();
}
}