java合并排序算法无法对对象集合进行排序

mi7gmzs6  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(174)

我正在编写一个合并排序算法,需要对一组对象进行排序。我不知道如何在不首先将集合转换为数组的情况下对集合进行排序。我希望算法能根据id号按升序对对象进行排序。算法必须返回集合而不是数组。我尝试获取的任何资源都是排序数组的算法,而不是集合。我已经在下面列出了我的代码。谢谢您。

private static Collection<Person> sortOne(Collection<Person> people) {
public void merge(int l, int m, int r) {
    int n1 = m - l + 1;
    int n2 = r - m;

    //Create temporary Arrays
    Person[] L = new Person[n1];
    Person[] R = new Person[n2];

//Copy data to temporary Arrays
    for(int i = 0; i < n1; i++)
        L[i] = persons[l + i];
    for(int j = 0; j < n2; j++)
        R[j] = persons[m + 1 + j];

    //Merge the temporary arrays    
    //Initial indexes of first and second subarrays
    int i = 0, j = 0;

    //Initial index of merged subarray persons
    int k = 1;
    while(i < n1 && j < n2) {
        if(L[i].getId() <= R[j].getId()) {
            persons[k] = L[i];
            i++;
        }
        else {
            persons[k] = R[j];
            j++;
        }
        k++;
    }

    //copy remaining elements of L[] if any
    while(i < n1) {
        persons[k] = L[i];
        i++;
        k++;
    }

    //Copy remaining elements of R[] if any
    while(j < n2) {
        persons[k] = R[j];
        j++;
        k++;

    }

}

    //sorting happens here
    //method to sort arrays of persons
    private void sort(Person persons[], int l, int r) {
    if(l < r) {
        //find the middle point
        int m = (l + r)/2;

        //sort first and second halves
        sort(persons, l, m);
        sort(persons, m + 1, r);

        //Merge the sorted halves
        merge(persons, l, m, r);

        for (int i = 0; i < persons.length; i++) {
            Person p = persons[i];
            System.out.println(p.getId());

        }
    }

    Collection<Person> people = Arrays.asList(persons);
    return;
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题