0

我无法将我的排序类转换为使用数组列表对对象进行排序。它目前正在对对象进行排序,但我无法将其转换为对 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];
        }

先感谢您!

4

2 回答 2

1

利用这个事实

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);
于 2012-05-31T03:36:39.007 回答
0

如果不是为了练习,您可以查看用于对 ArrayList 进行排序的Collections 排序方法。

于 2012-05-31T13:27:23.467 回答