其他分享
首页 > 其他分享> > 排序-冒泡排序

排序-冒泡排序

作者:互联网

冒泡排序思想

算法描述



代码实现(Java)
/**
 * @ClassName: BubbleSortMain
 * @Author: Ming
 * @Date: 2021/3/4 下午5:27
 * @Description: 冒泡排序
 */

import com.jiajia.ArrayUtil.*;  // 按包名导入

public class BubbleSortMain {

    public static void main(String[] args) {
        int[] arr = {2,5,1,3,8,5,7,4,3};
        bubbleSort(arr);

        ArrayUtil.print(arr);

    }

    /**
     * 冒泡排序
     * @param arr
     */
    private static void bubbleSort(int[] arr) {
        if(arr==null || arr.length < 2 ){
            return;
        }
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - i -1; j++) {   // 这里说明为什么需要-1
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
}

 

 

标签:arr,int,void,冒泡排序,bubbleSort,length,排序
来源: https://www.cnblogs.com/sponges/p/14485486.html