2018-11-14 01:15:47 +08:00
|
|
|
package Sorts;
|
2018-04-09 20:24:16 +08:00
|
|
|
|
2018-11-14 01:15:47 +08:00
|
|
|
import static Sorts.SortUtils.*;
|
2018-04-09 20:24:16 +08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @author Varun Upadhyay (https://github.com/varunu28)
|
|
|
|
* @author Podshivalov Nikita (https://github.com/nikitap492)
|
|
|
|
* @see SortAlgorithm
|
|
|
|
*/
|
|
|
|
|
2018-04-10 02:14:40 +08:00
|
|
|
class BubbleSort implements SortAlgorithm {
|
2018-04-09 20:24:16 +08:00
|
|
|
/**
|
|
|
|
* This method implements the Generic Bubble Sort
|
|
|
|
*
|
|
|
|
* @param array The array to be sorted
|
2019-05-09 19:32:54 +08:00
|
|
|
* Sorts the array in increasing order
|
2018-04-09 20:24:16 +08:00
|
|
|
**/
|
|
|
|
|
|
|
|
@Override
|
2019-05-09 19:32:54 +08:00
|
|
|
public <T extends Comparable<T>> T[] sort(T array[]) {
|
2019-09-26 10:02:58 +08:00
|
|
|
for (int i = 0, size = array.length; i < size - 1; ++i) {
|
|
|
|
boolean swapped = false;
|
|
|
|
for (int j = 0; j < size - 1 - i; ++j) {
|
|
|
|
swapped = less(array[j], array[j + 1]) && swap(array, j, j + 1);
|
2018-04-09 20:24:16 +08:00
|
|
|
}
|
2019-09-26 10:02:58 +08:00
|
|
|
if (!swapped) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
2018-04-09 20:24:16 +08:00
|
|
|
return array;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Driver Program
|
|
|
|
public static void main(String[] args) {
|
|
|
|
|
|
|
|
// Integer Input
|
2018-04-09 20:48:08 +08:00
|
|
|
Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12};
|
2018-04-09 20:24:16 +08:00
|
|
|
BubbleSort bubbleSort = new BubbleSort();
|
|
|
|
bubbleSort.sort(integers);
|
|
|
|
|
2018-05-29 17:44:14 +08:00
|
|
|
// Output => 231, 78, 54, 23, 12, 9, 6, 4, 1
|
2018-04-09 20:24:16 +08:00
|
|
|
print(integers);
|
|
|
|
|
|
|
|
// String Input
|
2019-05-09 19:32:54 +08:00
|
|
|
String[] strings = {"c", "a", "e", "b", "d"};
|
2018-05-29 17:44:14 +08:00
|
|
|
//Output => e, d, c, b, a
|
2018-04-09 20:24:16 +08:00
|
|
|
print(bubbleSort.sort(strings));
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|