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
|
2020-07-01 03:44:38 +08:00
|
|
|
* Sorts the array in ascending order
|
2018-04-09 20:24:16 +08:00
|
|
|
**/
|
|
|
|
|
|
|
|
@Override
|
2019-12-30 14:03:14 +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) {
|
2020-07-01 03:44:38 +08:00
|
|
|
if (greater(array[j], array[j + 1])) {
|
Update BubbleSort.java
Output from print(integers) returns [78, 231, 54, 23, 12, 9, 6, 4, 1]
Correct output should be: [231, 78, 54, 23, 12, 9, 6, 4, 1]
2019-11-24 01:22:27 +08:00
|
|
|
swap(array, j, j + 1);
|
|
|
|
swapped = true;
|
|
|
|
}
|
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);
|
|
|
|
|
2020-07-01 03:44:38 +08:00
|
|
|
// Output => 1, 4, 6, 9, 12, 23, 54, 78, 231
|
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"};
|
2020-07-01 03:44:38 +08:00
|
|
|
//Output => a, b, c, d, e
|
2018-04-09 20:24:16 +08:00
|
|
|
print(bubbleSort.sort(strings));
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|