Skip to content

Racket implementation for Bubble Sort #164

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from Jun 29, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ Maxime Dherbécourt
Jess 3Jane
Pen Pal
Chinmaya Mahesh
Unlambder
4 changes: 4 additions & 0 deletions book.json
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@
{
"lang": "go",
"name": "Go"
},
{
"lang": "racket",
"name": "Racket"
}
{
"lang": "m",
Expand Down
2 changes: 2 additions & 0 deletions chapters/sorting_searching/bubble/bubble_sort.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ This means that we need to go through the vector $$\mathcal{O}(n^2)$$ times with
[import:3-18, lang:"d"](code/d/bubble_sort.d)
{% sample lang="go" %}
[import:7-21, lang:"go"](code/go/bubbleSort.go)
{% sample lang="racket" %}
[import:5-19, lang:"racket"](code/racket/bubbleSort.rkt)
{% endmethod %}

... And that's it for the simplest bubble sort method.
Expand Down
21 changes: 21 additions & 0 deletions chapters/sorting_searching/bubble/code/racket/bubbleSort.rkt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#lang racket

(provide bubbleSort)


(define bubbleSort
(case-lambda [(l) (bubbleSort l (length l))]
[(l n) (if (= n 1)
l
(bubbleSort (pass l 0 n) (- n 1)))]))

; a single pass, if this is the nth pass, then we know that the (n - 1) last elements are already sorted
(define (pass l counter n)
(let ([x (first l)]
[y (second l)]
[r (drop l 2)])
(cond [(= (- n counter) 2) (cons (min x y) (cons (max x y) r))]
[(cons (min x y) (pass (cons (max x y) r) (+ counter 1) n))])))


((lambda (x) (display (bubbleSort x))) (read))