有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用合并排序对数组列表进行排序

我在将排序类转换为使用ArrayList排序对象时遇到问题。它目前正在对对象进行排序,但我无法将其转换为排序ArrayList。代码如下:

package Merge_Sort_Objects_ArrayList;
import java.util.ArrayList;
public class mergesort {

    /**
     * Merges two sorted portion of items array
     * pre: items[start.mid] is sorted.  items[mid+1.end] sorted.  start <= mid <= end
     * post: items[start.end] is sorted
     */

    private static void merge(ArrayList <Comparable> items, int start, int mid, int end){
            Comparable temp;
            int pos1 = start;
            int pos2 = mid + 1;
            int spot = start;
            ArrayList <Comparable> objectSort = items;

            while (!(pos1 > mid && pos2 > end)){
                if ((pos1 > mid) || ((pos2 <= end) &&(items[pos2].getRadius() < items[pos1].getRadius()))){
                    temp[spot] = items[pos2];
                    pos2 +=1;
                }else{
                    temp[spot] = items[pos1];
                    pos1 += 1;
                }
                spot += 1;
            }
            /* copy values from temp back to items */

            for (int i = start;  i <= end; i++){
                items[i] = temp[i];
            }
    }

    /**
     * mergesort items[start..end]
     * pre: start > 0, end > 0
     * post: items[start..end] is sorted low to high
     */
    public static void mergesort(ArrayList <Comparable> items, int start, int end){
        if (start < end){
            int mid = (start + end) / 2;
            mergesort(items, start, mid);
            mergesort(items, mid + 1, end);
            merge(items, start, mid, end);
        }
    }
}

现在我已经开始转换它,但我仍然停留在这一部分:

  while (!(pos1 > mid && pos2 > end)){
            if ((pos1 > mid) || ((pos2 <= end) &&(items[pos2].getRadius() < items[pos1].getRadius()))){
                temp[spot] = items[pos2];
                pos2 +=1;
            }else{
                temp[spot] = items[pos1];
                pos1 += 1;
            }
            spot += 1;
        }
        /* copy values from temp back to items */

        for (int i = start;  i <= end; i++){
            items[i] = temp[i];
        }

提前谢谢你


共 (2) 个答案

  1. # 1 楼答案

    如果不是为了练习,您可以查看排序ArrayList的Collections sort方法

  2. # 2 楼答案

    利用以下事实:

    Foo[] array = ......;
    Foo rhs = .....;
    Foo lhs;
    array[i] = rhs;
    lhs = array[j];
    

    类似于:

    ArrayList<Foo> list = .....;
    Foo rhs = ......;
    Foo lhs;
    list.set(i, rhs);
    lhs = list.get(i);