2016-09-24 68 views
0

我一直在堅持實現這個功能一段時間,現在,並找不到合適的資源來幫助我進一步。在方案中實現數字排序與追加函數

我想實現一個數字排序,按升序排序列表中的值。

我目前的實現是:

(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))))) 

我的理解是有問題的遞歸,在這裏,在那個時候我比較兩個元素,並決定做另一個遞歸調用,它完全搞砸了訂單 - 但我不知道如何解決這個問題。

在我的腦海中,我想要做的是通過比較每個元素與相鄰元素來組裝列表。通常情況下,我會嘗試通過以另一種語言存儲和訪問數組/變量的索引來做到這一點,但我無法圍繞如何在這一個中正確排序。

+0

哪個[排序算法(https://en.wikipedia.org/wiki/Sorting_algorithm)你想實現? – Renzo

+0

除插入排序外的任何內容。我不知道如何實現一個泡沫或合併排序與此。 –

+0

然後,您可以使用在此[page](http://www.cs.odu.edu/~zeil/cs355/Handouts/schemedoc/schemedoc/node16.html)中找到的Quicksort的實現。 – Renzo

回答

0

如果你想實現選擇排序,這裏是一個開始:

(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"