如何按排序顺序打印数组。 [英] How to print array in sorted order.

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

问题描述

如何在java中以数组的递增顺序显示数组项目?



输入

2

5

4

7



输出

2

4

5

7



我尝试过:



/ * package codechef; //不要放包名! * /



import java.util。*;

import java.lang。*;

import java .io。*;



/ *只有当班级公开时,班级名称必须为主。 * /

class Codechef

{

public static void main(String [] args)抛出java.lang.Exception

{

// System.out.println(输入要输入的数字的编号);

扫描仪s =新扫描仪(System.in );

int a = s.nextInt();

int digits [] = new int [a];

for(int i = 0; i< a; i ++)

{

扫描仪编号=新扫描仪(System.in);

int inputnumber = number。 nextInt();

digits [i] = inputnumber;

}

int max;

max = digits [0];

public int [] sort()

{

for(i = 0; i< a; j ++)

{

for(j = 0; i< ai; j ++)

{

if(digits [j] >数字[j + 1])

{

temp = digits [j];

digits [j] = digits [j + 1];

temp [j + 1] = temp;

}



}





}

返回数字;

}

Codechef obj =新Codechef();

obj.sort();



}

}

How to display items of array in increasing order of Array in java?

input
2
5
4
7

output
2
4
5
7

What I have tried:

/* package codechef; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// System.out.println("enter the no of number you want to enter");
Scanner s=new Scanner(System.in);
int a=s.nextInt();
int digits[]=new int[a];
for(int i=0;i<a;i++)
{
Scanner number=new Scanner(System.in);
int inputnumber=number.nextInt();
digits[i]=inputnumber;
}
int max;
max=digits[0];
public int[] sort()
{
for( i=0;i<a;j++)
{
for(j=0;i<a-i;j++)
{
if(digits[j]>digits[j+1])
{
temp=digits[j];
digits[j]=digits[j+1];
temp[j+1]=temp;
}

}


}
return digits;
}
Codechef obj=new Codechef();
obj.sort();

}
}

推荐答案

Arrays类包含一个名为sort的方法,用于对数组进行排序,这里有一个简单的例子



Arrays class contains a method named sort for sorting an array,here is a simple example

import java.util.Arrays;
class ArraysExample1
{
	public static void main(String args[])
	{
		int arr[] = {5,4,3,2,1};
		Arrays.sort(arr);
		for(int value:arr) { System.out.print(value+", ");}
	}
}





这将产生结果为1,2,3,4,5,



简要阅读:< a href =https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html>数组(Java Platform SE 7) [ ^ ]


使用行Arrays.sort(arrayname);
Use the line Arrays.sort(arrayname);


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

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