我的if条件出了什么问题?

时间:2013-04-18 02:24:20

标签: java sorting arraylist

我一直试图弄清楚这三个小时。我相信语法是正确的但方法不起作用。此类采用Point2D类型的ArrayList(类I定义),它保存点的x和y元素。我试图按升序点大小(例如(200,200),(200,400),(400,200),(400,300),(400,400)......等命令arrayList,所以排序x点,然后是y点)。 indexOfSmallest的for循环中的if条件最小,如果我正确应该工作,但它只会正确排序x值。有任何想法吗?提前谢谢!!

import java.util.ArrayList;

public class Point2DSelectionSort {
    public Point2DSelectionSort() {
    }

    public static void sort(ArrayList<Point2D> a) {
        int index, index2,indexOfNextSmallest;

            for (index = 0; index < a.size( ) - 1; index++){
              indexOfNextSmallest = 
                            indexOfSmallest(index, a);
              interchange(index,indexOfNextSmallest, a);
            }

            //a.get(0), a.get(1),...,a.get(index) are sorted.
     }

    /**
     * Precondition : i and j are legal indices for the ArrayList a.
     * Postcondition: a.get(i) and a.get(j) have been interchanged.
     */
     private static void interchange(
                                int i, int j, ArrayList<Point2D> a) {
        Point2D temp;
        temp = a.get(i);
        a.set(i, a.get(j));
        a.set(j, temp);
     }

    /**
     * @return  the index of the lexicographically first value among
     * a.get(startIndex), a.get(startIndex+1),...,a.get(a.size( ) - 1)
     */
    private static int indexOfSmallest(
                                 int startIndex, ArrayList<Point2D> a) {
        Point2D min = a.get(startIndex);
        int indexOfMin = startIndex;
        //Point2D otherPair = (Point2D) min;
        for (int index = startIndex + 1; index < a.size( ); index++){

            if((a.get(index).getFirst() < min.getFirst()) || (( a.get(index).getFirst() == min.getFirst() ) && ( a.get(index).getSecond() < min.getSecond() ))){
                   min = a.get(index);
                   indexOfMin = index; 
            }

        }
        return indexOfMin;
   }
}

1 个答案:

答案 0 :(得分:0)

您的整个课程都是不必要的,因为可以通过调用Collection.sort()

来取代它
List<Point2D> list; // assuming

Collections.sort(list, new Comparator<Point2D>() {
    public int compare(Point2D a, Point2D b) {
        return a.x == b.x ? a.y - b.y : a.x - b.x;
    }
});

瞧!


如果这是一个赋值,并且您必须使用该类,请将此代码合并到您的方法中(丢弃除排序方法之外的所有内容):

public static void sort(ArrayList<Point2D> a) {
    Collections.sort(list, new Comparator<Point2D>() {
        public int compare(Point2D a, Point2D b) {
            return a.x == b.x ? a.y - b.y : a.x - b.x;
        }
    });
}

完成工作。

要专门回答你的问题&#34;我的if语句&#34;有什么问题,答案是&#34;它存在&#34;。