2012-02-17 3 views
0

나는 답을 찾을 수 없다는 빠르고 간단한 질문을 가지고 있습니다.개체 배열 값을 메서드에 전달하는 방법

정수 배열을 정렬 할 수있는 quick_srt_int라는 메서드가 있습니다.하지만 내 배열은 개체에서 형성되었으며 특정 하위 값에서 배열을 정렬 할 수 있기를 원합니다. 이것이 어떻게 불려지는지).

배경을 지정하면 배열이 선언되는 방식입니다.

student[index] = new Person(name, id, age, gpa); 

다른 시간에 ID, 나이 및 GPA를 정렬 할 수 있어야하지만 값을 전달하는 방법을 알 필요가 없습니다. 내 생각 엔 이렇게 전달해야 할 것입니다 :

public void ageSort() { 
    quick_srt_int(student[].age, 0, student[].age.length - 1); 
} 

이 작업을 올바르게 수행하는 방법을 알려주십시오.

gpa가 이중 형식이고 정렬을 위해 캐스팅 할 수 없기 때문에 빠른 유형 정렬 방법을 수정하여 이중 유형 값을 지원해야합니다.

도움이 감사합니다. 정말 고마워요.

빠른 정렬 방법과 같이 보인다 : 당신은 Comparator을 찾고

public static void quick_srt_int(int array[], int low, int n) { 
    int lo = low; 
    int hi = n; 
    if (lo >= n) { 
     return; 
    } 
    int mid = array[(lo + hi)/2]; 
    while (lo < hi) { 
     while (lo < hi && array[lo] < mid) { 
      lo++; 
     } 
     while (lo < hi && array[hi] > mid) { 
      hi--; 
     } 
     if (lo < hi) { 
      int T = array[lo]; 
      array[lo] = array[hi]; 
      array[hi] = T; 
     } 
    } 
    if (hi < lo) { 
     int T = hi; 
     hi = lo; 
     lo = T; 
    } 
    quick_srt_int(array, low, lo); 
    quick_srt_int(array, lo == low ? lo + 1 : lo, n); 
} 

답변

0

@Logan에 따르면 Comparator를 사용해야하며 그렇지 않으면 Person 클래스가 Comparable 인터페이스를 구현해야합니다. 내가 당신에게 예를 들어주지 :

public class Person implements Comparable { 
    private String name; 
    private int id; 
    private int age; 
    private int gpa; 

    public Person(String name, int id, int age, int gpa) { 
     this.name = name; 
     this.id = id; 
     this.age = age; 
     this.gpa = gpa; 
    } 
    //getters and setters here... 

    //logic for the comparison 
    //NOTE: you can improve the comparison algorithm. 
    public int compareTo (Person p) { 
     //0 means both Person objects are equal. 
     // > 0 means **this** object is greater than p object. 
     // < 0 means **this** object is less than p object. 
     int result = 0; 
     //comparison by id 
     if (this.id > p.id) { 
      result = 1; 
     } else { 
      if (this.id < p.id) { 
       result = -1; 
      } else { //same id, check by age 
       if (this.age > p.age) { 
        result = 1; 
       } else { 
        if (this.age < p.age) { 
         result = -1; 
        } else { //same id and age, check by gpa 
         if (this.gpa > p.gpa) { 
          result = 1; 
         } else { 
          if (this.gpa < p.gpa) { 
           result = -1; 
          } 
         } 
        } 
       } 
      } 
     } 
    } 
    return result; 
} 

을 그리고 지금, 당신의 퀵 방법으로 사람의 배열을 보내 : 당신은 이것에 대한 비교 함수를 지정하려면

public void ageSort() { 
    quick_srt_int(student[], 0, student[].age.length - 1); 
} 

public static void quick_srt_int(Person array[], int low, int n) { 
    //your logic... 
} 

, 당신은 추가해야합니다 매개 변수를 quick_srt_int에 연결하면 Comparator 인터페이스를 구현하는 클래스를 설정할 수 있습니다.

+0

감사합니다. 나는 그것을 시도 할 것이다. :) –

0

. 당신의 문제와 매우 흡사 한 예가 있습니다 here

관련 문제