2017-05-02 8 views
-1

これを2回以上書き直すのですか、それとももっと効率的な方法がありますか? これについてはどうなりますか?価格と同じパターン(低から高)でソートするアイテムを取得するにはどうすればよいですか?2つの配列を同時に(選択ソートを使用して)ソートするにはどうすればよいですか? JAVA

public class W14_3 { 

    public static void main(String [] args){ 

     double[] price={73.25, 48.0, 345.0, 152.35, 196.50}; 
     String[] items={"bag", "stationary", "books", "shoes","clothing"}; 

     selectionSort(price , items); 
     for(int i = 0; i<price.length; i++) 
     System.out.println(price[i]); 

     for(int j=0; j<items.length; j++){ 
     System.out.println(items[j]); 
     } 

    } 

    public static void selectionSort(double[] P , String[] I){ 

     for(int startIndex=0; startIndex <P.length-1; startIndex++) 
     { 
      double min = P[startIndex]; 
      int indexOfMin = startIndex; 

      for(int j= startIndex +1; j< P.length; j++) 
       if(P[j] < min) 
       { 
        min =P[j]; 
        indexOfMin=j; 
        } 
      P[indexOfMin] = P[startIndex]; 
      P[startIndex] = min; 
       } 
     } 
    } 
} 
+0

個別の配列には物を持ってはいけません。アイテムを保持するクラスとそれに対応する価格を作成し、その配列を1つだけ持ちます。 –

答えて

0

あなたはほとんどそこにいる、私はあなたが数値と文字列は、クラスのメンバーであるクラスにあなたの配列を回すことをお勧めしたい考えます。例えば

public class someName { 
    public String getItem() { 
     return item; 
    } 

    public void setItem(String item) { 
     this.item = item; 
    } 

    public double getPrice() { 
     return price; 
    } 

    public void setPrice(double price) { 
     this.price = price; 
    } 

    private String item; 
    private double price; 

    public someName(String item, double price){ 
     this.item = item; 
     this.price = price; 
    } 
} 

ここで選択ソートに進むと、少し変更する必要があります。その後、あなたのmainメソッド内

public static void selectionSort(someName[] arr){ 
     for(int i = 0; i < arr.length-1; i++){ 
      int minIndex = i; // smallest element index 
      for(int j = i + 1; j < arr.length; j++){ 
       if(arr[j].getPrice() < arr[i].getPrice()){ // find smallest element 
        if(arr[j].getPrice() < arr[minIndex].getPrice()) 
         minIndex = j; // update smallest element index 
       } 
      } 

      if(i != minIndex){ // swap 
       someName temp = arr[minIndex]; 
       arr[minIndex] = arr[i]; 
       arr[i] = temp; 
      } 
     } 
} 

:どのようにSelection Sort作品と私はそのように行ってきた理由は、Selection Sortに私の以前の記事を参照してくださいに関する追加情報については

public static void main(String[] args) { 
     someName[] someIdentifier = new someName[5]; 
     someIdentifier[0] = new someName("bag",73.25); 
     someIdentifier[1] = new someName("stationary",48.0); 
     someIdentifier[2] = new someName("books",345.0); 
     someIdentifier[3] = new someName("shoes",152.35); 
     someIdentifier[4] = new someName("clothing",196.50); 
     selectionSort(someIdentifier); 
     for (someName item : someIdentifier) { 
      System.out.println(item.getItem() + " : " + item.getPrice()); 
     } 
} 

関連する問題