我写了这个程序来按升序排列数字。但它没有提供所需的输出。我已正确分析了该程序,并意识到我无法正确实现sort
函数(下面)。请建议应该如何正确输出该程序:
我在代码下面给出了示例输出:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class sorter
{
static int biggest;
static int arr[];
static int sortedArray[];
static int count;
public static void main(String args[]) throws IOException
{
System.out.print("How many numbers you want to enter : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String x = br.readLine();
try
{
count = Integer.parseInt(x);
}
catch (Exception exc)
{
System.out.println(exc);
}
arr = new int[count];
for (int i = 0; i < arr.length; i++)
{
System.out.print("Enter the " + (i + 1) + " number : ");
BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
try
{
arr[i] = Integer.parseInt(br2.readLine());
}
catch (Exception exc)
{
System.out.println(exc);
}
}
System.out.println("We'll sort the numbers now !");
sortedArray = new int[count];
biggest = getBiggest(arr[0]); // get The biggest number
for (int i = 0; i < arr.length; i++)
{
sortedArray[i] = sort(arr[0]);
}
for (int i = 0; i < sortedArray.length; i++)
{
System.out.println("SortedArray is : " + sortedArray[i]);
}
}
public static int getBiggest(int big)
{
for (int i = 1; i < arr.length; i++)
{
if (big < arr[i])
{
big = arr[i];
}
}
return big;
}
public static int sort(int small)
{
for (int i = 1; i < arr.length; i++)
{
if (small > arr[i])
{
small = arr[i];
System.out.println("BIGGEST-->" + biggest);
arr[i] =
++biggest; // i replace the smallest number with the biggest number after storing the smallest number in small
biggest++;
}
}
return small;
}
}
在此我没有得到所需的输出。我无法执行此任务。该程序中最大的问题是函数排序的工作。我怎样才能改善它的工作?这样它就会输出我想要的结果
How many numbers you want to enter : 4
Enter the 1 number : 6
Enter the 2 number : 7
Enter the 3 number : 8
Enter the 4 number : 1
We'll sort the numbers now !
BIGGEST-->8
SortedArray is : 1
SortedArray is : 6
SortedArray is : 6
SortedArray is : 6
How many numbers you want to enter : 6
Enter the 1 number : 6
Enter the 2 number : 8
Enter the 3 number : 55
Enter the 4 number : 99
Enter the 5 number : 44
Enter the 6 number : 557
We'll sort the numbers now !
SortedArray is : 6
SortedArray is : 6
SortedArray is : 6
SortedArray is : 6
SortedArray is : 6
SortedArray is : 6
答案 0 :(得分:1)
如何使用Arrays.sort()
?它会使你的代码更短:
//[...]
System.out.println("We'll sort the numbers now !");
Arrays.sort(arr);
for(int i : arr) {
System.out.println("SortedArray is : " + i);
}
答案 1 :(得分:1)
代码中的问题在
行中sortedArray[i] = sort(arr[0]);
您总是发送相同的元素,因为sort会返回数组中的一个或更大的元素。
也许你应该先得到一些想法。 Quicksort是最受欢迎的排序算法之一。
答案 2 :(得分:0)
为什么使用数组?只需使用集合,如List:
List<Integer> list = new ArrayList<Integer>();
... for all lines:
list.add(Integer.parseInt(br2.readLine()));
...
Collections.sort(list);
你已经完成了。这就是它的全部内容。