在main方法中读取5个整数值的数组。创建一个单独的函数,对数组进行排序并将数组返回到 main 方法并在那里打印。
到目前为止我已经做了:
import java.util.*;
public class arraysort {
public static void main(String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
int [] x = new int [5];
for (int i=0; i<5; i++) {
x[i] = in.nextInt();
}
}
public static int sortarray(int [] value) {
int max = value[0];
for (int i = 1; i < value.length; i++) {
//I am not sure after this point
//I just did the rest
int [] y = new int [5];
Scanner in = new Scanner (System.in);
value[i] = in.nextInt();
Arrays.sort(y);
System.out.println(y);
}
}
}
或者,如果您不想使用内置方法,也可以使用此 sortArray:
public static int[] sortarray(int [] value) {
for (int arrayIterator = 0; arrayIterator < value.length; arrayIterator++) {
for(int iterator2=arrayIterator+1; iterator2 < value.length; iterator2++) {
if(value[iterator2] < value[arrayIterator]) {
int temp=value[arrayIterator];
value[arrayIterator]=value[iterator2];
value[iterator2]=temp;
}
}
}
return value;
}
Arrays.toString()
和Arrays.sort()
赞助:
public class ArraySort
{
public static void main(String args[])
{
int t[] = {3, 5, 2}; // your reading part is fine, so I will skip it
sortArrayWithoutCheating(t);
System.out.println(Arrays.toString(t));
}
public static void sortArrayWithoutCheating(int[] t)
{
// simplest O(n^2) sort
for (int i = 0; i < t.length; i++)
{
for (int j = 0; j < i; j++)
{
if (t[i] < t[j])
{
// swap t[i] and t[j]
int temp = t[i];
t[i] = t[j];
t[j] = temp;
}
}
}
}
public static void sortArray(int[] t)
{
Arrays.sort(t);
}
}
输出:
[2, 3, 5]