Skip to content

Commit 524de7f

Browse files
Unlambderjiegillet
Unlambder
authored andcommitted
Racket implementation for Bubble Sort (#164)
* Added racket lang in book.json. * Added bubbleSort.rkt * Update bubble_sort.md * Update CONTRIBUTORS.md
1 parent b5af512 commit 524de7f

File tree

4 files changed

+28
-0
lines changed

4 files changed

+28
-0
lines changed

CONTRIBUTORS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@ Maxime Dherbécourt
99
Jess 3Jane
1010
Pen Pal
1111
Chinmaya Mahesh
12+
Unlambder

book.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,10 @@
8282
{
8383
"lang": "go",
8484
"name": "Go"
85+
},
86+
{
87+
"lang": "racket",
88+
"name": "Racket"
8589
}
8690
{
8791
"lang": "m",

chapters/sorting_searching/bubble/bubble_sort.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ This means that we need to go through the vector $$\mathcal{O}(n^2)$$ times with
3232
[import:3-18, lang:"d"](code/d/bubble_sort.d)
3333
{% sample lang="go" %}
3434
[import:7-21, lang:"go"](code/go/bubbleSort.go)
35+
{% sample lang="racket" %}
36+
[import:5-19, lang:"racket"](code/racket/bubbleSort.rkt)
3537
{% endmethod %}
3638

3739
... And that's it for the simplest bubble sort method.
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#lang racket
2+
3+
(provide bubbleSort)
4+
5+
6+
(define bubbleSort
7+
(case-lambda [(l) (bubbleSort l (length l))]
8+
[(l n) (if (= n 1)
9+
l
10+
(bubbleSort (pass l 0 n) (- n 1)))]))
11+
12+
; a single pass, if this is the nth pass, then we know that the (n - 1) last elements are already sorted
13+
(define (pass l counter n)
14+
(let ([x (first l)]
15+
[y (second l)]
16+
[r (drop l 2)])
17+
(cond [(= (- n counter) 2) (cons (min x y) (cons (max x y) r))]
18+
[(cons (min x y) (pass (cons (max x y) r) (+ counter 1) n))])))
19+
20+
21+
((lambda (x) (display (bubbleSort x))) (read))

0 commit comments

Comments
 (0)