先看代码
public class Main { public static void main(String[] args) { // TODO Auto-generated method stub int[] a = {9,5,4,3,7,3,2,1,2};//数据范围是0-10 for(int i = a.length-1;i>0;i--){ for(int j=0;j<i;j++){ if(a[j]>a[j+1]){ int temp = 0; temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } for(int i = 0;i<a.length;i++){ System.out.println(a[i]); } } }
还有一个方法
public class Main { public static void main(String[] args) { // TODO Auto-generated method stub int[] a = {9,5,4,3,7,3,2,1,2};//数据范围是0-10 int flag; for(int i = a.length-1;i>0;i--){ flag = 0; for(int j=0;j<i;j++){ if(a[j]>a[j+1]){ int temp = 0; temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; flag = 1; } } if(flag==0){ break; } } for(int i = 0;i<a.length;i++){ System.out.println(a[i]); } } }