JavaSE中你想看的例子——冒泡排序

冒泡排序

package chapter.three;

import java.util.Arrays;
public class Test02 {
    public static void main(String[] args) {
        int[] arr = {15,23,8,10,7};
        bubbleSort(arr);
        System.out.println(Arrays.toString(arr));
    }
    public static void bubbleSort(int[] a) {
        int n = a.length;
        //总共进行n-1轮的比较,i控制排序的轮数
        for (int i = 1; i < n; i++) { 
            //j是进行比较的第一个元素的下标
            for (int j = 0; j < n-1 ; j++) {//为什么要n-1,因为j+1会出现溢出,超出数组长度
                if (a[j] > a[j+1]) {//左>右,则交换
                    int temp = a[j];
                    a[j] = a[j+1];
                    a[j+1] = temp;
                }
            }
        }
    }
}

 

分析:

 

posted @ 2017-05-06 12:03  Java_皮卡丘漏电  阅读(109)  评论(0编辑  收藏  举报