X Tutup
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
55 changes: 55 additions & 0 deletions Sorts/BubbleSortRecursion.java
Original file line number Diff line number Diff line change
@@ -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 extends Comparable<T>> 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 <T extends Comparable<T>> 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);
}
}
}
X Tutup