fix: handle empty inputs in CircleSort (#5121)

* fix: handle empty inputs in `CircleSort`

* style: remove `main` method
This commit is contained in:
Piotr Idzik 2024-05-05 20:26:54 +02:00 committed by GitHub
parent 6bde5d7ed5
commit 5d00889291
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 11 additions and 17 deletions

View File

@ -10,6 +10,9 @@ public class CircleSort implements SortAlgorithm {
@Override @Override
public <T extends Comparable<T>> T[] sort(T[] array) { public <T extends Comparable<T>> T[] sort(T[] array) {
int n = array.length; int n = array.length;
if (n == 0) {
return array;
}
while (doSort(array, 0, n - 1)) { while (doSort(array, 0, n - 1)) {
} }
return array; return array;
@ -50,21 +53,4 @@ public class CircleSort implements SortAlgorithm {
return swapped || leftHalf || rightHalf; return swapped || leftHalf || rightHalf;
} }
/* Driver code*/
public static void main(String[] args) {
CircleSort CSort = new CircleSort();
Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12};
CSort.sort(arr);
for (int i = 0; i < arr.length - 1; ++i) {
assert arr[i] <= arr[i + 1];
}
String[] stringArray = {"c", "a", "e", "b", "d"};
CSort.sort(stringArray);
for (int i = 0; i < stringArray.length - 1; ++i) {
assert arr[i].compareTo(arr[i + 1]) <= 0;
}
}
} }

View File

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