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:
Aslan Autlev
2023-07-19 18:56:40 +03:00
committed by GitHub
parent 4dddd5aa83
commit 022d97a56d
2 changed files with 51 additions and 0 deletions

View 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

View File

@@ -0,0 +1,37 @@
(define (find-smallest my-list)
(let ((smallest (list-ref my-list 0))
(smallest-i 0)
(i 0)
(last-index (- (length my-list) 1)))
(iter-find my-list smallest-i smallest i last-index)))
(define (iter-find my-list smallest-i smallest i last-index)
(if (> i last-index)
smallest-i
(let ((my-list-i (list-ref my-list i)))
(if (< my-list-i smallest)
(iter-find my-list i my-list-i (+ i 1) last-index)
(iter-find my-list smallest-i smallest (+ i 1) last-index)))))
(define (selection-sort my-list)
(let* ((my-list-length (length my-list))
(result (list))
(i 0)
(last-i (- my-list-length 1)))
(iter-sort my-list i last-i result)))
(define (iter-sort my-list i last-i result)
(if (> i last-i)
result
(let* ((smallest-i (find-smallest my-list))
(smallest (list-ref my-list smallest-i))
(filtered-list (filter (lambda (n) (not (= n smallest)))
my-list))
(new-result (append result (list smallest))))
(iter-sort filtered-list (+ i 1) last-i new-result))))
(display (selection-sort (list 1 3 5 7 9))) ;; #(1 3 5 7 9)
(display (selection-sort (list 9 7 5 3 1))) ;; #(1 3 5 7 9)
(display (selection-sort (list 9 5 7 1 3))) ;; #(1 3 5 7 9)