首页 > 编程语言 > 详细

冒泡排序

时间:2021-05-26 21:37:52      阅读:26      评论:0      收藏:0      [点我收藏+]
public class BubbleSortTest {
    public static void main(String[] args) {

        int[] arrays = {1,5,3,4,7,8,6,12};
        int[] ints = bubbleSort(arrays);
        System.out.println(Arrays.toString(ints));
    }
    public static int[] bubbleSort(int[] array){
        int temp = 0;//临时变量temp
        boolean flag = false;//通过flag标识为减少没有意义的比较
        /*外层循环判断两两要比较多少次*/
        for (int i = 0; i < array.length; i++) {
            /*内层循环,比较判断两个数,如果第一个数比第二个数大,则交换两个数的位置*/
            for (int j = 0; j < array.length-1-i; j++) {
                if (array[j]>array[j+1]){
                    temp = array[j];
                    array[j]=array[j+1];
                    array[j+1]=temp;
                    flag = true;
                }
            }
            if (flag==false){
                break;
            }
        }
        return array;
    }
}

运算结果:
技术分享图片

冒泡排序

原文:https://www.cnblogs.com/guoguodong/p/14814766.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!