/** * @desc:冒泡排序 * @author: 毛会懂 * @create: 2020-12-23 11:39:00 **/ public class Bubbling { public static void sort(Comparable[] arr){ for(int i = arr.length -1; i > 0;i--){ //只冒泡到第i个元素就行了,因为后面的元素已经有序 for(int j = 0;j < i;j++){ if(isExchange(arr[j],arr[j+1])){ swap(arr,j,j+1); } } } } private static Boolean isExchange(Comparable o1,Comparable o2){ return o1.compareTo(o2) > 0; } private static void swap(Comparable[] arr,int i,int j){ Comparable temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } //冒泡排序 public static void main(String[] args) { Integer[] arr = {10,8,20,30,5,7,4,12,40,30,1,2,4,3,100,5,32,45,23,66,45,7,55,79,6}; Bubbling.sort(arr); Arrays.asList(arr).forEach(System.out::println); }
本文参考链接:https://www.cnblogs.com/maohuidong/p/14179422.html