Skip to content

Commit 492826d

Browse files
committed
Bubble sort implementation for Lisp
1 parent ba85d61 commit 492826d

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

CONTRIBUTORS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,3 +58,4 @@ Michal Hanajik
5858
<br>
5959
Bendik Samseth
6060
Trashtalk
61+
Trashtalk
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
;;;;Bubble sort implementation
2+
3+
;;;Swaps to elements in a list (complexity: O(n))
4+
(defun swap (lst low high)
5+
(let ((list-tail (nthcdr low lst)))
6+
(rotatef (car list-tail) (elt list-tail (- high low)))
7+
lst))
8+
9+
(defun bubble_sort (lst)
10+
(dotimes (m (- (length lst) 1) lst) ;loop
11+
(dotimes (n (- (length lst) (+ 1 m)) lst) ;loop
12+
(if (> (nth n lst) (nth (+ n 1) lst)) ;if
13+
(swap lst n (+ n 1)) ;then
14+
lst)))) ;else
15+
16+
;;Use of an array insead of a list would be faster
17+
;;The built-in sort is also quicker (sort (list 5 4 3 2 1))
18+
(print (bubble_sort (list 5 4 3 2 1)))

0 commit comments

Comments
 (0)