From 022d97a56d3e4b56dce958b55f9652660717d292 Mon Sep 17 00:00:00 2001 From: Aslan Autlev Date: Wed, 19 Jul 2023 18:56:40 +0300 Subject: [PATCH] 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 --- .../scheme/01_binarysearch.scm | 14 +++++++ .../scheme/01_selection_sort.scm | 37 +++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 01_introduction_to_algorithms/scheme/01_binarysearch.scm create mode 100644 02_selection_sort/scheme/01_selection_sort.scm diff --git a/01_introduction_to_algorithms/scheme/01_binarysearch.scm b/01_introduction_to_algorithms/scheme/01_binarysearch.scm new file mode 100644 index 0000000..6652510 --- /dev/null +++ b/01_introduction_to_algorithms/scheme/01_binarysearch.scm @@ -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 diff --git a/02_selection_sort/scheme/01_selection_sort.scm b/02_selection_sort/scheme/01_selection_sort.scm new file mode 100644 index 0000000..e6d3e72 --- /dev/null +++ b/02_selection_sort/scheme/01_selection_sort.scm @@ -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)