JavaAlgorithms/Sorts/BubbleSort.java

54 lines
1.3 KiB
Java
Raw Normal View History

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
* Sorts the array in increasing order
2018-04-09 20:24:16 +08:00
**/
@Override
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;
for (int count = 0; count < last - 1; count++) {
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
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
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));
}
}