package test; public class Maopao { public static void main(String[] args) { int array[]=new int[]{0,8,-6,5,7,8,5}; int[] smalltobig = smalltobig(array); for (int i : smalltobig) { System.out.println(i); } int[] bigtosmall = bigtosmall(array); System.out.println("-------------------------------"); for (int i : bigtosmall) { System.out.println(i); } } public static int[] smalltobig(int[] a) { for (int i = 0; i < a.length-1; i++) { for (int j = i+1; j < a.length; j++) {//a[i]每次都是循环拿到最小值,所以内嵌for循环的起始值为a[i+1] if(a[i]>a[j]){ int temp=a[i]; a[i]=a[j]; a[j]=temp; } } } return a; } public static int[] bigtosmall(int[] b) { for (int i = 0; i < b.length-1; i++) { for (int j = i+1; j < b.length; j++) {//a[i]每次都是循环拿到最大值,所以内嵌for循环的起始值为a[i+1] if(b[i]<b[j]){ int temp=b[i]; b[i]=b[j]; b[j]=temp; } } } return b; } }
从大到小:从第一个元素开始,依次和后面的每一个元素相比较,每次找出剩余元素中最大的;
从大到小:从第一个元素开始,依次和后面的每一个元素相比较,每次找出剩余元素中最小的;
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/7527.html