1

これは、マージソートを使用したリストの私の実装です:

public class List {

        private final Object data;
        private final List next;
        public static final List NIL = new List(null, null);

        private List(Object d, List n) {
                data = d;
                next = n;
        }

        public static List list(Object d) {
                return new List(d, List.NIL);
        }

        public List append(List that) {
                return this.isEmpty() ?
                        that :
                        this.tail().append(that).push(this.head());
        }

        public Object nth(int n) {
                return this.isEmpty() || n < 0 ? null :
                                n == 0 ? this.head() :
                                this.tail().nth(n-1);
        }

        public List sort() {
                return mergesort(0, this.length());
        }

        private List mergesort(int top, int out) {
                List l = null;
                if (top < out - 1) {
                        int mid = (top + out) / 2;
                        mergesort(top, mid);
                        mergesort(mid, out);
                        l = merge(top, mid, out);
                }
                return l;
        }

        private List merge(int top1, int top2, int out) {
                List temp = List.NIL;
                List toReturn = this;
                int i = top1;
                int j = top2;
                int k = 0;

                while (i < top2 && j < out) {
                        Comparable one = (Comparable) this.nth(i);
                        Comparable two = (Comparable) this.nth(j);
                        if (one.compareTo(two) < 0) {
                                temp = temp.append(List.list(this.nth(i++)));
                        } else {
                                temp = temp.append(List.list(this.nth(j++)));
                        }
                }

                while (i < top2) temp = temp.append(List.list(this.nth(i++)));
                while (j < out) temp = temp.append(List.list(this.nth(j++)));

                for (k = 0; k < temp.length(); k++)
                        toReturn = toReturn.append(List.list(temp.nth(k)));

                return toReturn;

        }

}

このコードはマージソートを適切に実装しているように見えますが、ソート時に間違った結果が6 5 4 3 2 1得られます : が得られ3 2 1 6 5 4、理由がわかりません。まだ見たことのない小さなことなのか、それとも根本的な問題なのかはわかりません。

4

0 に答える 0