Java 按增加的顺序排列数字
我正在编写一个程序,在数组中排列元素,最大值在最末端,当元素在数组中向后移动时,其大小会减小。我可以把它们排在最小的第一位,以此类推,但我想看看是否可以换一种方式。下面是我的代码。它在第一次迭代之后不起作用。谁能帮帮我吗Java 按增加的顺序排列数字,java,Java,我正在编写一个程序,在数组中排列元素,最大值在最末端,当元素在数组中向后移动时,其大小会减小。我可以把它们排在最小的第一位,以此类推,但我想看看是否可以换一种方式。下面是我的代码。它在第一次迭代之后不起作用。谁能帮帮我吗 import java.util.Scanner;//Importing scanner class. import java.util.Arrays;//Importing the array class. { public static void main(Str
import java.util.Scanner;//Importing scanner class.
import java.util.Arrays;//Importing the array class.
{
public static void main(String[] args)
{
double [] numbers= {5,3,6,4,1};
double currentMax;
int currentMaxIndex;
int i,j,k;
// Scanner input = new Scanner(System.in);//Creating a scanner.
//The below lines are used to ask the user to enter 10 numbers.
/* for (k = 0;k<numbers.length;k++)
{
System.out.print("Enter number " + k +" : ");
numbers[k]=input.nextDouble();
}//end of for loop.
*/
for(i=numbers.length-1;i>1;i--)
{
currentMax=numbers[i];
currentMaxIndex=i;
for(j=numbers.length-2;j>0;j--)
{
if(currentMax<numbers[j])
{currentMax=numbers[j];
currentMaxIndex=j;
}
}
if(currentMaxIndex!=i)
{
numbers[currentMaxIndex]=numbers[i];
numbers[i]=currentMax;
}
}
System.out.print("The sorted new array is:\n");
for(i=0;i<numbers.length;i++)
{
System.out.print(numbers[i]+" ");
}
}
}
虽然它不能直接回答您的问题,但它确实提供了一种合理的替代方法 按如下方式重构代码: 步骤1:删除所有代码 第2步:键入以下内容:
Arrays.sort(numbers);
显然有更好的排序方法,但我认为这应该可以修复您的代码:
外部循环应该检查i>=1,内部循环检查j>=0。您要查找的是一个简单的插入排序。Arrays.sortnumbers,Collections.reverseOrder;如果他想要降序,我从他的问题上看不出来。如果要使用此方法,需要更改为Double[]number=new Double[]{5,3,6,4,1.};还有。我需要安排从最末端开始,然后是第二大,以此类推。@atomman他希望从最低到最高,他试图从最后到第一处理,但是array.sort会做他想做的事情array sort会工作,但我需要做这件事作为我任务的一部分。我想做这件事,但我只是被困在某个地方。我不是那种喜欢从网上复制结果的人。我想先了解一下。