2010-03-26 88 views
0

好的,我試圖列入清單並從最大到最小排序。計劃整理清單

Example: 
> (maxheap (list 5 6 2 1 18 7)) 
;output: 
> (18 7 6 5 2 1) 

因此,這裏是我走到這一步:

(define (mkmaxheap heaplist) 
    (let ((max (mymax(heaplist)))) 
    ;mymax is a func that returns max number, it works 

    (let ((head (car heaplist)) (tail (cdr heaplist))) 
     (if (null? tail) 
     newlist)))) 

這就是所有我能得到編譯,其他所有的代碼我寫失敗。任何幫助解決這個將不勝感激。

回答

2

你應該清楚地說明你想用來生成排序列表的策略。是這樣的嗎?

  • 查找列表中的最大數量。
  • 獲取列表中除最大值以外的其餘部分。
  • 對列表的其餘部分進行排序,並將最大值放在它的前面。

這不是一個非常快速的方法來排序,但它應該工作。代碼的下一步是編寫一個函數來獲取除最大值之外的其他列表(如果列表中有重複項,請正確處理它)。

一旦寫完了,應該是能夠寫出與上述輪廓類似或多或少的Scheme代碼。

1

這是Common lisp中的合併排序算法。這大致接近於在計劃中實施相同的排序。

(defun merge-sort(input) 
    (labels ((right-half (input) 
      (last input (ceiling (/ (length input) 2)))) 
      (left-half (input) 
      (ldiff input (right-half input)))) 
    (if (or (null input) (null (cdr input))) 
     input 
     (merge 'list (merge-sort (left-half input)) (merge-sort (right-half input)) #'<)))) 
1

您需要決定如何使用排序列表。最近我一直在對方案進行修改,通過SICP和「Schemer」系列工作,我發現在方案中實現泡泡排序,合併排序和快速排序非常簡單。

1

你沒有指定你正在使用的實現。但它可以執行r6rs list-sortsrfi-95 sort或任何其他內置排序。查看你的實現文檔。