聊聊排序(二)—— 冒泡排序(Bobble Sort)
冒泡排序
import cn.hutool.core.util.ArrayUtil;
import java.util.Arrays;
/**
* @author NOknow
* @version 1.0
* @date 2020/09/08
*/
public class BubbleSort {
@SuppressWarnings({"all"})
public static void sortAsc(Comparable[] data) {
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data.length - i - 1; j++) {
if (data[j].compareTo(data[j + 1]) > 0) {
ArrayUtil.swap(data, j, j + 1);//一个交换数组中两个位置的数据的工具类而已
}
}
}
}
public static void main(String[] args) {
Integer[] integers = {16, 33, 20, 5, 39, 7, 20, 9, 10, 31};
System.out.println(Arrays.toString(integers));
sortAsc(integers);
System.out.println(Arrays.toString(integers));
}
}
控制台输出:
[16, 33, 20, 5, 39, 7, 20, 9, 10, 31]
[5, 7, 9, 10, 16, 20, 20, 31, 33, 39]