001.冒泡算法(涉及到冒泡排序的优化)
package com.lll.demo; import javax.sound.midi.Soundbank; public class Demo5 { public static void main(String[] args) { int number[] = {9, 7, 5, 3, 1, 10, 8, 6, 4, 2}; // System.out.println(number.length); for (int i = 0; i < number.length - 1; i++) {//比较趟数,需要走元素个数减去一 boolean swap = false;//假设没有进行交换 for (int j = 0; j < number.length - i - 1; j++)//比较次数(number.length - i)是每趟的比较次数,减一是为了不让number[j + 1]下标越界 { if (number[j] > number[j + 1]) { int temp = number[j]; number[j] = number[j + 1]; number[j + 1] = temp; swap = true;//一旦进行交换就该百年swap的值 } } if (!swap)//数组已经有序,跳出当前训话 { break; } } for (int i = 0;i <10 ; ++i) { System.out.print(" "+number[i]); } } }