在Racket中插入排序,无法弄清楚为什么这不起作用

时间:2016-11-16 00:33:47

标签: recursion scheme racket insertion-sort

我是Racket的新手,我正在试图找出插入排序。这就是我所拥有的,但我收到了一个错误,我无法从调试中弄明白。

let encode = function (x) {

    function _enc(x, lst) {
        if (typeof x !== 'object')
            return x;

        let i = lst.indexOf(x);
        if (i >= 0)
            return {'->': i};
        lst.push(x);

        let y = {};
        for (let k of Object.keys(x))
            y[k] = _enc(x[k], lst)

        return y;
    }

    return JSON.stringify(_enc(x, []));
};

//////

let ones = [1];
ones[1] = ones;

let ones_ = [1];
ones_[1] = ones_;

console.log(encode(ones) === encode(ones_))

// more interesting example

a = {
    b: {
        c: 123
    }
};

a.b.d = a;
a.x = [9, a.b];


a2 = {
    b: {
        c: 123
    }
};

a2.b.d = a2;
a2.x = [9, a2.b];

console.log(encode(a) === encode(a2))

2 个答案:

答案 0 :(得分:0)

以下功能工作:

(define (insert n l cmp (ol '()))
  (cond
    [(empty? l)
     (append ol (list n))] ; or: (reverse (cons n (reverse ol)))
    [(not (cmp n (first l)))
     (append ol (list n) l)]
    [else (insert n
                  (rest l)
                  cmp
                  (append ol (list (first l))) ; or:  (reverse (cons (first l) (reverse ol)))
                  )] ))

(define (isort l cmp (sl '()))
  (cond
    [(empty? l) sl]
    [else (isort (rest l)
                 cmp
                 (insert (first l)
                         sl
                         cmp))] ))

这些函数似乎是尾递归的。

测试:

(isort '(4 2 5 8 1 4 7 3 6 9) >)
(isort '(4 2 5 8 1 4 7 3 6 9) <)

输出:

'(1 2 3 4 4 5 6 7 8 9)
'(9 8 7 6 5 4 4 3 2 1)

答案 1 :(得分:0)

insert中使用insertionSort时,您已“翻转”(define (insertionSort L1 cmp) (cond ((null? L1) L1) (else (insert cmp (insertionSort (cdr L1) cmp) (car L1))))) 的参数;它应该是

iterator.next()