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[]) {
|
2018-04-09 20:24:16 +08:00
|
|
|
int last = array.length;
|
|
|
|
//Sorting
|
|
|
|
boolean swap;
|
|
|
|
do {
|
|
|
|
swap = false;
|
2019-05-09 19:32:54 +08:00
|
|
|
for (int count = 0; count < last - 1; count++) {
|
2018-04-09 20:48:08 +08:00
|
|
|
if (less(array[count], array[count + 1])) {
|
|
|
|
swap = swap(array, count, count + 1);
|
2018-04-09 20:24:16 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
last--;
|
|
|
|
} while (swap);
|
|
|
|
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));
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|