将int []数组从大到小排序

时间:2017-03-06 21:50:24

标签: java arrays int

我想对数字进行排序,以便输出为:[12,9,8,7,5,4,3,1] 请帮忙;)

int[] array = new int[]{8,5,3,7,9,12,4,1};
int biggest = 0;
for (int i =0; i<array.length;i++){
    if(array[i]>biggest){
        biggest = array[i];
    }
}
System.out.println(biggest); //Outputs 12

3 个答案:

答案 0 :(得分:2)

在java 8中使用流:

int[] array = new int[]{8,5,3,7,9,12,4,1};
int max = Arrays.stream(array).max().getAsInt();

答案 1 :(得分:0)

试试这个:

    int[] array = new int[]{8,5,3,7,9,12,4,1};
    Arrays.sort(array);
    for (int i =array.length -1; i>=0;i--){
      System.out.println(array[i]);
    }

还有溪流:

int[] array = new int[]{8,5,3,7,9,12,4,1};
Arrays.stream(array).boxed()
    .sorted(Comparator.reverseOrder()).forEach(System.out::println);

答案 2 :(得分:0)

使用冒泡排序来组织数组:

int a, b, t;
int size = array.length;

for(a=1; a < size; a++)
    for(b=size-1; b >= a; b--){
        if(array[b-1] > array[b]){ //If out of order
           t = array[b-1];
           array[b-1] = array[b];
           array[b] = t;
          }
   }

然后颠倒顺序,使其从最高到最低:

  for(int i = 0; i < array.length / 2; i++)
    {
        int temp = array[i];
        array[i] = array[array.length - i - 1];
        array[array.length - i - 1] = temp;
    }