1.升序排序
int a[]=new int[] {10,3,5,6,7,1,2};
Arrays.sort(a);
for(int i:a)
System.out.print(i+" ");
2.降序排序
可以使用倒序输出,或者倒序存入新的数组。
//倒序输出
for(int j=a.length-1;j>=0;j--) {
System.out.print(a[j]+" ");
}
//存入新的数组
int b[]=new int[a.length];
for(int k=0;k<a.length;k++) {
b[k]=a[a.length-1-k];
}
for(int k:b) {
System.out.print(k+" ");
}
直接冒泡排序:
int a[]=new int[] {10,3,5,6,7,1,2};
int temp;
for(int i=0;i<a.length-1;i++) {
for(int j=0;j<a.length-i-1;j++) {
if(a[j]<a[j+1]) {
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}