From 6da8a0098633266de1be3a0aff8855435ffdfabb Mon Sep 17 00:00:00 2001 From: shellhub Date: Wed, 12 Aug 2020 00:37:16 +0800 Subject: [PATCH 1/2] BubbleSort Recursion --- Sorts/BubbleSortRecursion.java | 55 ++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Sorts/BubbleSortRecursion.java diff --git a/Sorts/BubbleSortRecursion.java b/Sorts/BubbleSortRecursion.java new file mode 100644 index 00000000..6af7778f --- /dev/null +++ b/Sorts/BubbleSortRecursion.java @@ -0,0 +1,55 @@ +package Sorts; + +import java.util.Random; + +/** + * BubbleSort algorithm implements using recursion + */ +public class BubbleSortRecursion implements SortAlgorithm { + public static void main(String[] args) { + Integer[] array = new Integer[10]; + + Random random = new Random(); + /* generate 10 random numbers from -50 to 49 */ + for (int i = 0; i < array.length; ++i) { + array[i] = random.nextInt(100) - 50; + } + + BubbleSortRecursion bubbleSortRecursion = new BubbleSortRecursion(); + bubbleSortRecursion.sort(array); + + /* check array is sorted or not */ + for (int i = 0; i < array.length - 1; ++i) { + assert (array[i].compareTo(array[i + 1]) <= 0); + } + } + + /** + * @param unsorted - an array should be sorted + * @return sorted array + */ + @Override + public > T[] sort(T[] unsorted) { + bubbleSort(unsorted, unsorted.length); + return unsorted; + } + + /** + * BubbleSort algorithm implements using recursion + * + * @param unsorted array contains elements + * @param len length of given array + */ + private static > void bubbleSort(T[] unsorted, int len) { + boolean swapped = false; /* flag to check if array is sorted or not */ + for (int i = 0; i < len - 1; ++i) { + if (SortUtils.greater(unsorted[i], unsorted[i + 1])) { + SortUtils.swap(unsorted, i, i + 1); + swapped = true; + } + } + if (swapped) { + bubbleSort(unsorted, len - 1); + } + } +} From ea34a0302576cf69bca597ecd0edda006a61fee1 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 11 Aug 2020 16:37:48 +0000 Subject: [PATCH 2/2] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 03b29c69..f0981af0 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -202,6 +202,7 @@ * [BitonicSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BitonicSort.java) * [BogoSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BogoSort.java) * [BubbleSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BubbleSort.java) + * [BubbleSortRecursion](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BubbleSortRecursion.java) * [BucketSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BucketSort.java) * [CocktailShakerSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CocktailShakerSort.java) * [CombSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CombSort.java)