2017-05-02 1 views
-1

그냥 두 번 이상 다시 작성 하시겠습니까? 아니면 더 효율적인 방법이 있습니까? 이 작업을 수행하겠습니다. 가격이 낮은 패턴에서 높은 패턴으로 정렬되는 항목을 어떻게 얻을 수 있습니까?선택 정렬을 사용하여 동시에 두 개의 배열을 정렬 할 수 있습니까? 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

별도의 배열에 항목이 없어야합니다. 항목을 보관할 클래스와 해당 가격을 만들고 그 배열을 하나만 가져야합니다. –

답변

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; 
    } 
} 

이제 선택 사항 정렬을 진행하면 조금 변경해야합니다. 다음 메인 메소드 내

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()); 
     } 
} 

.