我正在按照第一个元素排序列表列表,例如
(排序(列表'(2 1 6 7)'(4 3 1 2 4 5)'(1 1))))
预期输出=> ('(11)'(2 1 6 7)'(4 3 1 2 4 5))
我使用的算法是冒泡排序。我修改它来处理列表。但是,代码没有编译。错误是
mcar: contract violation
expected: mpair?
given: 4
有人可以更正我的代码并解释它。谢谢
(define (bubble L)
(if (null? (cdr L))
L
(if (< (car (car L)) (car (cadr L)))
(list (car L)
(bubble (car (cdr L))))
(list (cadr L)
(bubble (cons (car (car L)) (car (cddr L))))))))
(define (bubble-sort N L)
(cond ((= N 1) (bubble L))
(else
(bubble-sort (- N 1) (bubble L)))))
(define (bubble-set-up L)
(bubble-sort (length L) L))
(define t3 (list '(2 1 6 7) '(4 3 1 2 4 5) '(1 2 3) '(1 1)))
(bubble-set-up t3)
答案 0 :(得分:2)
(sort (lambda (x y)(< (car x)(car y))) <YOUR_LIST>)
怎么样?
答案 1 :(得分:2)
我修正了一些错误。至少还有一个错误。
考虑L
仅包含一个元素的情况。
#lang r5rs
(define (bubble L)
(if (null? (cdr L))
L
(if (< (car (car L)) (car (cadr L)))
(cons (car L)
(bubble (cdr L)))
(cons (cadr L)
(bubble (cons (car L) (cddr L)))))))
(define (bubble-sort N L)
(cond ((= N 1) (bubble L))
(else
(bubble-sort (- N 1) (bubble L)))))
(define (bubble-set-up L)
(bubble-sort (length L) L))
(define t3 (list '(2 1 6 7) '(4 3 1 2 4 5) '(1 2 3) '(1 1)))
(display (bubble-set-up t3))
(newline)