Add examples on scheme. Chapters: 1, 2 (#258)
* add 01_binary_search.scm in 01_introduction_to_algorithms * any fix * add 01_selection_sort.scm to 02_selection_sort * any fix
This commit is contained in:
14
01_introduction_to_algorithms/scheme/01_binarysearch.scm
Normal file
14
01_introduction_to_algorithms/scheme/01_binarysearch.scm
Normal file
@@ -0,0 +1,14 @@
|
||||
(define (binary-search my-list item)
|
||||
(iter my-list item 0 (- (length my-list) 1)))
|
||||
|
||||
(define (iter my-list item low high)
|
||||
(if (> low high) 'nill
|
||||
(let* ((mid (floor (/ (+ low high) 2)))
|
||||
(guess (list-ref my-list mid)))
|
||||
(cond ((eqv? guess item) mid)
|
||||
((> guess item) (iter my-list item low (- mid 1)))
|
||||
(else (iter my-list item (+ mid 1) high))))))
|
||||
|
||||
|
||||
(display (binary-search (list 1 3 5 7 9) 3)) ;; 1
|
||||
(display (binary-search (list 1 3 5 7 9) -1)) ;; nill
|
||||
Reference in New Issue
Block a user