码迷,mamicode.com
首页 > 编程语言 > 详细

冒泡排序

时间:2020-07-07 22:13:45      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:i++   array   void   color   冒泡   system   位置   作用   数字   

用两个for来实现

两个for的作用 :单拎出来一个,与未排序的数字比较去掉,如果后面的值小于本身,则互换

  例如:1 3 2

拎出来 2 与前面的数字比较,碰到 3 了

  3赋值给临时变量temp;

  2放到3的位置上去,temp放到原来2的位置上去

 

import java.util.Arrays;

public class maobao_sort {
    public static void main(String[] args) {
        int[] a = {1,4,6,99,45,34};
        int[] sort = sort(a);
        System.out.println(Arrays.toString(sort));
    }

    public static int[] sort(int[] array){
        int temp = 0;
        for(int i=0; i<array.length-1; i++){        //i<array.length是不变的
            for(int j=0; j<array.length-i-1; j++){      //j< 的值却不断变化,因为内循环每次确定一个最大值
                if(array[j + 1] < array[j]){        //只需比较前面没有排序的
                    temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
                }
            }
        }
        return array;
    }
}

 

冒泡排序

标签:i++   array   void   color   冒泡   system   位置   作用   数字   

原文地址:https://www.cnblogs.com/qiuyehaha/p/13263592.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!