[英]Implementing Number Sort with Append Function in Scheme
現在,我確實一直在實現此功能上停留了一段時間,並且找不到合適的資源來進一步幫助我。
我正在嘗試實現一個數字排序,該列表以升序對列表中的值進行排序。
我當前的實現是:
(define num-sort
(lambda (ls)
(if(null? (cdr ls))
ls
(if(< (car ls) (cadr ls))
(append (car ls) (num-sort(cdr ls)))
(if(> (car ls) (cadr ls))
(append (num-sort(cdr ls)) (car ls))
(num-sort(cdr ls))
)))))
我在計划方面花了很長時間,並且從邏輯上理解事情的完成方式。
我的“附加”功能是我在此之前實現的功能,它似乎可以正常工作:
(define append
(lambda (ls1 ls2)
(if (null? ls1)
ls2
(if (pair? ls1)
(cons (car ls1) (append (cdr ls1) ls2))
(cons ls1 ls2)))))
我知道遞歸存在問題,因為當我比較兩個元素並決定進行另一個遞歸調用時,它完全弄亂了順序-但是我不確定如何解決這個問題。
在我的腦海中,我想做的是通過將每個元素與相鄰元素進行比較來組裝列表。 通常,我會嘗試通過以另一種語言存儲和訪問數組/變量的索引來做到這一點,但是我無法將精力集中在如何在該語言中正確排序。
如果您想實現選擇排序,請從以下開始:
(define (num-sort ls)
(if (null? ls)
ls
(num-sort-helper (car ls) '() (cdr ls))))
(define (num-sort-helper min-so-far checked unchecked)
# min-so-far is no bigger than anything in checked
# nothing in unchecked has been looked at
# return a list made up of min-so-far and the elements of
# checked and unchecked such that that first element returned
# is no bigger than anything else in that list
# For example, (num-sort-helper 5 '(6 9 7) '(8 2 3)) returns
# a list of all 7 numbers with 2 at the beginning
(cond ((null? unchecked) ???) # nothing is bigger than min-so-far
((<= min-so-far (car unchecked)) ???) # min-so-far is still the "winner"
(else ???))) # (car unchecked) is now the "winner"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.