Bubble Sort in Common Lisp

"Bubble Sort" is usually first sorting algorithm beginners stumble upon when learning about in algoritms part in "Data Structure and Algorithm".

In real-life to understand this one quick example can be, suppose you are given a group of humans and your job is to arrange them in order of height i.e. smallest person first and tallest one should be last. What you are going to do is, ask them stand in a line. Now take the first person and compare height of first person with height of second person. If First person is taller, then you swap their position. If not, you proceed and compare first person's height with next person. If first person is taller, than you swap their position otherwise you move on to next. If no person smaller then first person is found then you have found it's right position.

Now you repeat above process, but this time you start from second peson and use same steps. This way you put the second person in right position.

Repeat this process and each time, start with one position higher than position used in previous step. In the end you ends up arranging all the person in order of their heights.

So, how you do it in Common Lisp. You create a function which takes list as argumnent. Measure the length to know how many times you have to iterate the list. We have run two loops, one to make sure we process all elements and second one to really compare and swap the elements of the list. See code below:

(defun bubble-sort (x)
  (let ((l (length x)))
    (dotimes (n l)
      (let ((swapped nil))
       (dotimes (m (- l 1))
         (let ((num1 (nth m x))          ; get number at current index
               (num2 (nth (+ m 1) x)))   ; get number at current index + 1
           (if (> num1 num2)             ; if current number is larger than next, then swap the values.
               (let ((temp num1))
                 (setf (nth m x) num2)
                 (setf (nth (+ m 1) x) temp)
                 (setf swapped T)))
           ))
       (when (not swapped)               ; exit if, list is already sorted.
         (return x))))))