2013-10-26 14 views
-3

我正在編寫一個程序,將數組中的元素排列成最大值,然後在數組中向後移動時大小會減小。我可以安排他們最小的首先等等,但我想看看我能否做相反的事情。下面是我的代碼。它不會超越第一次迭代。任何人都可以幫助我。安排數字以便增加

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]+" "); 
    } 
    } 
} 
+0

你在找什麼是一個簡單的插入排序。 – Tdorno

回答

0

雖然它不直接回答你的問題,但它確實提供了一個合理的替代方法。

重構代碼如下:

第1步:刪除所有的代碼

第2步:輸入這個:

Arrays.sort(numbers); 
+0

'Arrays.sort(numbers,Collections.reverseOrder());'如果他想要降序(我無法從他的問題中得知)。如果你想使用這種方法,你需要改爲'Double [] numbers = new Double [] {5。,3.,6.,4.,1。};'。 – atomman

+0

我需要從最後開始排列,然後是第二大排序,等等。 – user2918968

+0

@atomman他希望它從最低到最高(他試圖*最後處理*,但Arrays.sort()會做他想做的事) – Bohemian

0

顯然有更好的方式來排序,但我認爲這應該修復您的代碼:

外部循環應檢查i >= 1和內部循環j >= 0

相關問題