冒泡排序是所有排序中最简单的,背都可以背下来的代码,不用过多解释了。就是把相邻的两个数互相比较,如果左边的数大于右边的数,就把这两个数交换位置。
1 package com.liuyunfei.test; 2 3 import java.util.Arrays; 4 5 public class BubbleSort { 6 public void sort(int a[]){ 7 for(int i=0;i<a.length;i++){ 8 for(int j=0;j<a.length-1;j++){ 9 if(a[j]>a[j+1]){ 10 int temp=a[j]; 11 a[j]=a[j+1]; 12 a[j+1]=temp; 13 } 14 } 15 } 16 } 17 public static void main(String[] args) { 18 int a[]={6,5,7,8,3,2,1,5,6,7,9,0}; 19 new BubbleSort().sort(a); 20 System.out.println(Arrays.toString(a)); 21 } 22 }
执行结果