Java的:排序数组 [英] Java: Sort an array

查看:125
本文介绍了Java的:排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个程序,由一个数组的10个整数,所有具有随机值,到目前为止,一切顺利。

不过,现在我需要他们进行排序从最低到最高值,然后打印到屏幕上,我将如何去这样做?

(对不起,我有这么多的code的程序小,我是不是与循环好,刚开始使用Java)

 公共静态无效的主要(字符串ARGS [])
{
    INT []数组=新INT [10];    阵列[0] =((int)的(的Math.random()* 100 + 1));
    阵列[1] =((int)的(的Math.random()* 100 + 1));
    阵列[2] =((int)的(的Math.random()* 100 + 1));
    阵列[3] =((int)的(的Math.random()* 100 + 1));
    阵列[4] =((int)的(的Math.random()* 100 + 1));
    阵列[5] =((int)的(的Math.random()* 100 + 1));
    阵列[6] =((int)的(的Math.random()* 100 + 1));
    阵列[7] =((int)的(的Math.random()* 100 + 1));
    阵列[8] =((int)的(的Math.random()* 100 + 1));
    阵列[9] =((int)的(的Math.random()* 100 + 1));    的System.out.println(数组[0] ++阵列[1] ++阵列[2] ++阵列[3]
    ++阵列[4] ++阵列[5] ++阵列[6] ++阵列[7] +
    +阵列[8] ++阵列[10]);}


解决方案

循环也非常有用的了解,尤其当使用阵列,

  INT []数组=新INT [10];
随机兰特=新的随机();
的for(int i = 0; I< array.length,我++)
    数组[我] = rand.nextInt(100)+ 1;
Arrays.sort(数组);
的System.out.println(Arrays.toString(阵列));
//以相反的顺序
的for(int i = array.length - 1; I> = 0;我 - )
    System.out.print(数组[I] +);
的System.out.println();

I'm trying to make a program that consists of an array of 10 integers which all has a random value, so far so good.

However, now I need to sort them in order from lowest to highest value and then print it onto the screen, how would I go about doing so?

(Sorry for having so much code for a program that small, I ain't that good with loops, just started working with Java)

public static void main(String args[])
{
    int [] array = new int[10];

    array[0] = ((int)(Math.random()*100+1));
    array[1] = ((int)(Math.random()*100+1));
    array[2] = ((int)(Math.random()*100+1));
    array[3] = ((int)(Math.random()*100+1));
    array[4] = ((int)(Math.random()*100+1));
    array[5] = ((int)(Math.random()*100+1));
    array[6] = ((int)(Math.random()*100+1));
    array[7] = ((int)(Math.random()*100+1));
    array[8] = ((int)(Math.random()*100+1));
    array[9] = ((int)(Math.random()*100+1));

    System.out.println(array[0] +" " + array[1] +" " + array[2] +" " + array[3]
    +" " + array[4] +" " + array[5]+" " + array[6]+" " + array[7]+" " 
    + array[8]+" " + array[9] );        

}

解决方案

Loops are also very useful to learn about, esp When using arrays,

int[] array = new int[10];
Random rand = new Random();
for (int i = 0; i < array.length; i++)
    array[i] = rand.nextInt(100) + 1;
Arrays.sort(array);
System.out.println(Arrays.toString(array));
// in reverse order
for (int i = array.length - 1; i >= 0; i--)
    System.out.print(array[i] + " ");
System.out.println();

这篇关于Java的:排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆