使用所需的递归细节进行排序

时间:2014-12-12 01:35:08

标签: java sorting loops recursion

我目前的困境是我试图让一个arraylist通过使用递归进行排序,因为当前代码是这样的:

class Student {
    private String name;
    private int finalExam;

    public Student(String n, int points) {
        name = n;
        finalExam = points;
    }

    public int finalExam() {
        return finalExam;
    }

    public String name() {
        return name;
    }

    public String toString() {
        return name + " " + finalExam;
    }

}

public class assignment {

    private static int minFinalExam(List<Student> students, int first) {
        int smallest;
        int gradeOfFirst = students.get(first).finalExam();
        if (first == students.size() - 1)
            smallest = gradeOfFirst; // the base case
        else { // the general case:
            int minOfRest = minFinalExam(students, first + 1);
            if (minOfRest < gradeOfFirst)
                smallest = minOfRest;
            else
                smallest = gradeOfFirst;
        }
        return smallest;
    }

    private static int smallestOf(List<Student> list, int first, int last) {
        int smallest;
        int gradeOfFirst = list.get(first).finalExam();
        if (first == last)
            smallest = gradeOfFirst; // the base case
        else {// the general case:
            int minOfRest = minFinalExam(list, first + 1);
            if (minOfRest < gradeOfFirst)
                smallest = minOfRest;
            else
                smallest = gradeOfFirst;
        }
        return smallest;

    }

    private static void interchange(List<Student> list, int m, int n) {
    }

    private static void selectionSort(List<Student> list, int first) {
        if (first < list.size()) {
            int small = smallestOf(list, first, list.size() - 1);
            interchange(list, first, small);
            selectionSort(list, first + 1);
        }
    }

    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<Student>();
        // list.add elements here 6 times that are in the format ("Name", score_of_Final)       
        System.out.println("List: " + list);
        // the unsorted list
        selectionSort(list, 0);
        System.out.println("Sorted List: " + list);

    }
}

现在我必须将代码放在交换方法中才能对它进行排序,但我似乎无法弄清楚要放什么。请帮助我是初学者。

0 个答案:

没有答案