JavaAlgorithms/Sorts/BubbleSort.java

56 lines
1.4 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 {
2020-10-24 18:23:28 +08:00
/**
* Implements generic bubble sort algorithm.
2020-10-24 18:23:28 +08:00
*
* @param array the array to be sorted.
* @param <T> the type of elements in the array.
* @return the sorted array.
2020-10-24 18:23:28 +08:00
*/
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
for (int i = 0, size = array.length; i < size - 1; ++i) {
boolean swapped = false;
for (int j = 0; j < size - 1 - i; ++j) {
if (greater(array[j], array[j + 1])) {
swap(array, j, j + 1);
swapped = true;
2019-09-26 10:02:58 +08:00
}
2020-10-24 18:23:28 +08:00
}
if (!swapped) {
break;
}
2018-04-09 20:24:16 +08:00
}
2020-10-24 18:23:28 +08:00
return array;
}
2018-04-09 20:24:16 +08:00
/** Driver Code */
2020-10-24 18:23:28 +08:00
public static void main(String[] args) {
2018-04-09 20:24:16 +08:00
2020-10-24 18:23:28 +08:00
Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12};
BubbleSort bubbleSort = new BubbleSort();
bubbleSort.sort(integers);
2018-04-09 20:24:16 +08:00
for (int i = 0; i < integers.length - 1; ++i) {
assert integers[i] <= integers[i + 1];
}
print(integers); /* output: [1, 4, 6, 9, 12, 23, 54, 78, 231] */
2018-04-09 20:24:16 +08:00
2020-10-24 18:23:28 +08:00
String[] strings = {"c", "a", "e", "b", "d"};
bubbleSort.sort(strings);
for (int i = 0; i < strings.length - 1; i++) {
assert strings[i].compareTo(strings[i + 1]) <= 0;
}
print(bubbleSort.sort(strings)); /* output: [a, b, c, d, e] */
2020-10-24 18:23:28 +08:00
}
2018-04-09 20:24:16 +08:00
}