mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-07 09:45:04 +08:00
fix: avoid infinite loop in SwapSort
(#5248)
--------- Co-authored-by: vil02 <65706193+vil02@users.noreply.github.com>
This commit is contained in:
@ -17,8 +17,8 @@ public class SwapSort implements SortAlgorithm {
|
|||||||
while (index < len - 1) {
|
while (index < len - 1) {
|
||||||
int amountSmallerElements = this.getSmallerElementCount(array, index);
|
int amountSmallerElements = this.getSmallerElementCount(array, index);
|
||||||
|
|
||||||
if (amountSmallerElements > 0 && index != amountSmallerElements) {
|
if (amountSmallerElements > 0) {
|
||||||
SortUtils.swap(array, index, amountSmallerElements);
|
SortUtils.swap(array, index, index + amountSmallerElements);
|
||||||
} else {
|
} else {
|
||||||
index++;
|
index++;
|
||||||
}
|
}
|
||||||
@ -29,7 +29,7 @@ public class SwapSort implements SortAlgorithm {
|
|||||||
|
|
||||||
private <T extends Comparable<T>> int getSmallerElementCount(T[] array, int index) {
|
private <T extends Comparable<T>> int getSmallerElementCount(T[] array, int index) {
|
||||||
int counter = 0;
|
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])) {
|
if (SortUtils.less(array[i], array[index])) {
|
||||||
counter++;
|
counter++;
|
||||||
}
|
}
|
||||||
@ -37,36 +37,4 @@ public class SwapSort implements SortAlgorithm {
|
|||||||
|
|
||||||
return counter;
|
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
8
src/test/java/com/thealgorithms/sorts/SwapSortTest.java
Normal file
8
src/test/java/com/thealgorithms/sorts/SwapSortTest.java
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
package com.thealgorithms.sorts;
|
||||||
|
|
||||||
|
public class SwapSortTest extends SortingAlgorithmTest {
|
||||||
|
@Override
|
||||||
|
SortAlgorithm getSortAlgorithm() {
|
||||||
|
return new SwapSort();
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user