1
- ; ;;;Bubble sort implementation
1
+ ; ;;; Bubble sort implementation
2
2
3
- ; ;;Swaps to elements in a list (complexity: O(n))
3
+ ; ;; Swaps two elements in a list (complexity: O(n))
4
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))
5
+ (let ((list-tail (nthcdr low lst)))
6
+ (rotatef (car list-tail) (elt list-tail (- high low)))
7
+ lst))
8
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
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
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 )))
16
+ ; ; Use of an array instead of a list would be faster
17
+ (print
18
+ (bubble-sort (list 5 4 3 2 1 )))
19
+ (print
20
+ (bubble-sort (list 1 2 3 3 2 1 )))
21
+
22
+ ; ; The built-in sort is quicker, see the usage below
23
+ ; ; quick test
24
+ (assert
25
+ (equal (bubble-sort (list 5 4 3 2 1 ))
26
+ (sort ' (1 2 3 4 5 ) #' < )))
27
+
28
+ (assert
29
+ (equal (bubble-sort (list 1 2 3 3 2 1 ))
30
+ (sort ' (1 2 3 3 2 1 ) #' < )))
0 commit comments