Skip to content

fix: avoid infinite loop in SwapSort #5248

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 24, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 12 additions & 51 deletions src/main/java/com/thealgorithms/sorts/SwapSort.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,64 +9,25 @@
*/
public class SwapSort implements SortAlgorithm {

/**
* Sorts the input array using the swap sort algorithm.
*
* @param array the array to be sorted
* @param <T> the type of elements in the array, which must be Comparable
* @return the sorted array
*/
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
int len = array.length;
int index = 0;

while (index < len - 1) {
int amountSmallerElements = this.getSmallerElementCount(array, index);

if (amountSmallerElements > 0 && index != amountSmallerElements) {
SortUtils.swap(array, index, amountSmallerElements);
} else {
index++;
for (int i = 0; i < len - 1; i++) {
for (int j = i + 1; j < len; j++) {
if (SortUtils.less(array[j], array[i])) {
SortUtils.swap(array, i, j);
}
}
}

return array;
}

private <T extends Comparable<T>> int getSmallerElementCount(T[] array, int index) {
int counter = 0;
for (int i = 0; i < array.length; i++) {
if (SortUtils.less(array[i], array[index])) {
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 changes: 8 additions & 0 deletions src/test/java/com/thealgorithms/sorts/SwapSortTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.thealgorithms.sorts;

public class SwapSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new SwapSort();
}
}