From 5d00889291f21930af03a414691bfc069565c3f9 Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Sun, 5 May 2024 20:26:54 +0200 Subject: [PATCH] fix: handle empty inputs in `CircleSort` (#5121) * fix: handle empty inputs in `CircleSort` * style: remove `main` method --- .../com/thealgorithms/sorts/CircleSort.java | 20 +++---------------- .../thealgorithms/sorts/CircleSortTest.java | 8 ++++++++ 2 files changed, 11 insertions(+), 17 deletions(-) create mode 100644 src/test/java/com/thealgorithms/sorts/CircleSortTest.java diff --git a/src/main/java/com/thealgorithms/sorts/CircleSort.java b/src/main/java/com/thealgorithms/sorts/CircleSort.java index 7f2dc5fd..c6a6d9ea 100644 --- a/src/main/java/com/thealgorithms/sorts/CircleSort.java +++ b/src/main/java/com/thealgorithms/sorts/CircleSort.java @@ -10,6 +10,9 @@ public class CircleSort implements SortAlgorithm { @Override public > T[] sort(T[] array) { int n = array.length; + if (n == 0) { + return array; + } while (doSort(array, 0, n - 1)) { } return array; @@ -50,21 +53,4 @@ public class CircleSort implements SortAlgorithm { 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; - } - } } diff --git a/src/test/java/com/thealgorithms/sorts/CircleSortTest.java b/src/test/java/com/thealgorithms/sorts/CircleSortTest.java new file mode 100644 index 00000000..d1134732 --- /dev/null +++ b/src/test/java/com/thealgorithms/sorts/CircleSortTest.java @@ -0,0 +1,8 @@ +package com.thealgorithms.sorts; + +class CircleSortTest extends SortingAlgorithmTest { + @Override + SortAlgorithm getSortAlgorithm() { + return new CircleSort(); + } +}