-
Notifications
You must be signed in to change notification settings - Fork 14
/
BubbleSort.java
37 lines (32 loc) · 1.06 KB
/
BubbleSort.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package by.andd3dfx.sorting;
/**
* @see <a href="https://youtu.be/vK4BTGVELwk">Video solution</a>
*/
public class BubbleSort {
public static <T extends Comparable> void apply(T[] array) {
var sorted = false;
while (!sorted) {
sorted = true;
for (var i = 1; i < array.length; i++) {
if (array[i].compareTo(array[i - 1]) < 0) {
swap(array, i, i - 1);
sorted = false;
}
}
}
}
public static <T extends Comparable> void apply2(T[] array) {
for (var outIndex = array.length - 1; outIndex > 0; outIndex--) {
for (var inIndex = 0; inIndex < outIndex; inIndex++) {
if (array[inIndex].compareTo(array[inIndex + 1]) > 0) {
swap(array, inIndex, inIndex + 1);
}
}
}
}
private static <T> void swap(T[] array, int i, int j) {
var tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}