2015-11-11 3 views
1

Итак, у меня есть этот код, чтобы быстро отсортировать список учащихся по классам.Добавление дополнительных критериев сортировки в быстрый сортировки в java

public static void quickSort(Student[] school){ 
    quickSort(school, 0, school.length - 1);    // quicksort all the elements in the array 
} 

private static void quickSort(Student[] school, int start, int end) { 
    int i = start;       // index of left-to-right scan 
    int k = end;       // index of right-to-left scan 

    if (end - start >= 1) // check that there are at least two elements to sort 
    { 
     Student pivot = school[start];  // set the pivot as the first element in the partition 

     while (k > i) // while the scan indices from left and right have not met, 
     { 
      while (school[i].getStudentGrade() <= pivot.getStudentGrade() && i <= end && k > i) // from the left, look for the first 
      { 
       i++; 
                // element greater than the pivot 
      } 
      while (school[k].getStudentGrade() > pivot.getStudentGrade() && k >= start && k >= i) // from the right, look for the first 
      { 
       k--;          // element not greater than the pivot 
      } 
      if (k > i) // if the left seekindex is still smaller than 
      { 
       swap(school, i, k);      // the right index, swap the corresponding elements 
      } 
     } 
     swap(school, start, k);   // after the indices have crossed, swap the last element in 
     // the left partition with the pivot 
     quickSort(school, start, k - 1); // quicksort the left partition 
     quickSort(school, k + 1, end); // quicksort the right partition 
    } else // if there is only one element in the partition, do not do any sorting 
    { 
     return;      // the array is sorted, so exit 
    } 
} 

//Swap 2 index values in array 
private static void swap(Student[] school, int index1, int index2) 
{ 
    Student temp = school[index1];   
    school[index1] = school[index2];  
    school[index2] = temp;    
} 

Я только не могу понять, как добавить дополнительные критерии сортировки, чтобы студенты с теми же сортами сортируются на основе там числа студентов, которые я получаю с помощью student.getStudentNumber.

+3

Одним из способов является абстрактным ваше сравнение в отдельный метод. Таким образом, ваш алгоритм сортировки не должен изменяться только потому, что вы меняете критерии сортировки. Один типичный подход заключается в том, чтобы метод сортировки возвращал один из значений {-1,0,1}, в зависимости от того, является ли первый аргумент меньше, равным или большим, чем второй аргумент. –

+0

@ AndyThomas: Это именно то решение. Добавьте это как ответ, например. Я подниму его. –

+0

Спасибо за помощь! –

ответ

2

Вместо прямого использования функции сравнения отправьте java.util.Comparator<T>. Таким образом вы можете реализовать различные Comparator s для разных критериев сортировки.

Компаратор будет выглядеть следующим образом:

import java.util.Comparator; 

public class StudentComparator implements Comparator<Student> { 

    @Override 
    public int compare(final Student s1, final Student s2) { 
     final int gradeDiff = s1.getStudentGrade() - s2.getStudentGrade(); 
     if (0 != gradeDiff) { 
      return gradeDiff; 
     } 
     final int numberDiff = s1.getStudentNumber() - s2.getStudentNumber(); 
     if (0 != numberDiff) { 
      return numberDiff; 
     } 
     // addd mor criteria here if wanted 
     return 0; 
    } 
} 
+0

Показать пример. –

0

Используется это сейчас

public class QuickSort { 

    public static void quickSort(Student[] school) { 
     quickSort(school, 0, school.length - 1);    
    } 

    private static void quickSort(Student[] school, int start, int end) { 
     int pivotIndex = start; 
     int storeIndex = pivotIndex + 1; 

     if (end - start >= 1) { 

      for (int i = pivotIndex + 1; i <= end; i++) { 
       if (school[i].getStudentGrade() > school[pivotIndex].getStudentGrade()) { 
        swap(school, storeIndex, i); 
        storeIndex++; 
       } else if(school[i].getStudentGrade() == school[pivotIndex].getStudentGrade()){ 
        if(school[i].getStudentNumber() > school[pivotIndex].getStudentNumber()){ 
         swap(school, storeIndex, i); 
         storeIndex ++; 
        } 
       } 
      } 
      swap(school, pivotIndex, storeIndex - 1); 
      pivotIndex = storeIndex - 1; 
      quickSort(school, start, pivotIndex - 1); 
      quickSort(school, pivotIndex + 1, end); 
     } else { 
      return; 
     } 
    } 

    //Swap 2 index values in array 

    private static void swap(Student[] school, int index1, int index2) { 
     Student temp = school[index1]; 
     school[index1] = school[index2]; 
     school[index2] = temp; 
    } 
} 
Смежные вопросы