JavaAlgorithms/Sorts/BubbleSortRecursion.java

54 lines
1.4 KiB
Java
Raw Normal View History

2020-08-12 00:37:16 +08:00
package Sorts;
import java.util.Random;
2020-10-24 18:23:28 +08:00
/** BubbleSort algorithm implements using recursion */
2020-08-12 00:37:16 +08:00
public class BubbleSortRecursion implements SortAlgorithm {
2020-10-24 18:23:28 +08:00
public static void main(String[] args) {
Integer[] array = new Integer[10];
2020-08-12 00:37:16 +08:00
2020-10-24 18:23:28 +08:00
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;
}
2020-08-12 00:37:16 +08:00
2020-10-24 18:23:28 +08:00
BubbleSortRecursion bubbleSortRecursion = new BubbleSortRecursion();
bubbleSortRecursion.sort(array);
2020-08-12 00:37:16 +08:00
2020-10-24 18:23:28 +08:00
/* check array is sorted or not */
for (int i = 0; i < array.length - 1; ++i) {
assert (array[i].compareTo(array[i + 1]) <= 0);
2020-08-12 00:37:16 +08:00
}
2020-10-24 18:23:28 +08:00
}
2020-08-12 00:37:16 +08:00
2020-10-24 18:23:28 +08:00
/**
* @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;
}
2020-08-12 00:37:16 +08:00
2020-10-24 18:23:28 +08:00
/**
* 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);
2020-08-12 00:37:16 +08:00
}
2020-10-24 18:23:28 +08:00
}
2020-08-12 00:37:16 +08:00
}