在方案中对列表进行排序 [英] Sorting a list in scheme

查看:46
本文介绍了在方案中对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写一个排序算法,以递增顺序返回列表.

How do write a sorting algorithm that returns a list into increasing order.

例如:'(1 3 5 2 9) 返回 '(1 2 3 5 9)

推荐答案

大多数 Scheme 实现都带有对列表进行排序的过程.如果您的实现没有提供一个,那么在您身上滚动一个并不困难.这是快速排序算法的实现:

Most Scheme implementations come with a procedure to sort lists. If your implementation does not provide one, it is not difficult to roll one on your on. Here is an implementation of the quick-sort algorithm:

> (define (qsort e)
  (if (or (null? e) (<= (length e) 1)) e
      (let loop ((left null) (right null)
                   (pivot (car e)) (rest (cdr e)))
            (if (null? rest)
                (append (append (qsort left) (list pivot)) (qsort right))
               (if (<= (car rest) pivot)
                    (loop (append left (list (car rest))) right pivot (cdr rest))
                    (loop left (append right (list (car rest))) pivot (cdr rest)))))))
> (qsort  '(1 3 5 2 9))
=> (1 2 3 5 9)

这篇关于在方案中对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆