我正在編寫一個程序,將數組中的元素排列成最大值,然後在數組中向後移動時大小會減小。我可以安排他們最小的首先等等,但我想看看我能否做相反的事情。下面是我的代碼。它不會超越第一次迭代。任何人都可以幫助我。安排數字以便增加
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]+" ");
}
}
}
你在找什麼是一個簡單的插入排序。 – Tdorno