ZetCode

Scheme sorting

last modified November 25, 2026 Guile 3.0

Sorting puts the elements of a sequence in order. This article writes the classic algorithms for Scheme lists: insertion sort, quicksort, and merge sort. It then makes them work with any order by passing a comparison procedure, counts their work, sorts vectors in place, and finishes with the sorting procedures that Guile provides. The examples are run with GNU Guile 3.0.7.

Insertion sort

Insertion sort builds the result one element at a time. Its core is a procedure that inserts a number into a list that is already sorted.

insertion.scm
(define (insert-sorted x sorted)
  (cond ((null? sorted) (list x))
        ((<= x (car sorted)) (cons x sorted))
        (else (cons (car sorted) (insert-sorted x (cdr sorted))))))

(define (insertion-sort lst)
  (if (null? lst)
      '()
      (insert-sorted (car lst) (insertion-sort (cdr lst)))))

(display (insert-sorted 5 '(1 3 7 9)))
(newline)
(display (insertion-sort '(31 4 15 9 26 5 3)))
(newline)
(display (insertion-sort '()))
(newline)

insert-sorted walks the sorted list until it finds an element that is not smaller than x and puts x before it. insertion-sort sorts the rest of the list recursively and inserts the first element into the result. The empty list is already sorted. Each insertion may walk the whole list, so the algorithm takes time proportional to n2 for n elements.

$ guile insertion.scm
(1 3 5 7 9)
(3 4 5 9 15 26 31)
()

Quicksort

Quicksort picks one element, the pivot, and divides the other elements into those smaller than the pivot and the rest. Each part is sorted recursively, and the parts are joined with the pivot in between. With lists and filter from the higher-order procedures article, the algorithm is a direct translation of this description.

quicksort.scm
(define (quicksort lst)
  (if (or (null? lst) (null? (cdr lst)))
      lst
      (let ((pivot (car lst))
            (rest (cdr lst)))
        (append (quicksort (filter (lambda (x) (< x pivot)) rest))
                (list pivot)
                (quicksort (filter (lambda (x) (>= x pivot)) rest))))))

(display (quicksort '(31 4 15 9 26 5 3)))
(newline)
(display (quicksort '(2 7 1 8 2 8 1 8)))
(newline)

A list with fewer than two elements is returned unchanged. The pivot is the first element. The elements smaller than the pivot go to the left part, the others, including duplicates of the pivot, to the right part. append joins the sorted parts. The second call shows that duplicates are kept.

$ guile quicksort.scm
(3 4 5 9 15 26 31)
(1 1 2 2 7 8 8 8)

Merge sort

Merge sort splits the list into two halves, sorts each half, and merges the two sorted halves into one sorted list. Merging is cheap: it compares only the first elements of the two lists.

mergesort.scm
(use-modules (srfi srfi-1))

(define (merge-lists a b)
  (cond ((null? a) b)
        ((null? b) a)
        ((< (car b) (car a))
         (cons (car b) (merge-lists a (cdr b))))
        (else
         (cons (car a) (merge-lists (cdr a) b)))))

(define (merge-sort lst)
  (if (or (null? lst) (null? (cdr lst)))
      lst
      (let ((half (quotient (length lst) 2)))
        (merge-lists (merge-sort (take lst half))
                     (merge-sort (drop lst half))))))

(display (merge-lists '(1 4 9) '(2 3 10 11)))
(newline)
(display (merge-sort '(31 4 15 9 26 5 3)))
(newline)
(display (merge-sort '(5 4 3 2 1 0)))
(newline)

merge-lists takes the smaller of the two first elements and merges the rest. When one list is empty, the other one is the result. merge-sort splits the list with take and drop from the SRFI 1 list library. Each level of splitting halves the lists, so there are about log2(n) levels, and each level merges n elements. Merge sort takes time proportional to n log n whatever the input.

$ guile mergesort.scm
(1 2 3 4 9 10 11)
(3 4 5 9 15 26 31)
(0 1 2 3 4 5)

Comparison procedures

The sorts so far use < and work only for numbers in ascending order. Passing the comparison as an argument makes one sort procedure work for any type and any order. The comparison, usually called less?, returns true when its first argument must come before the second.

comparator.scm
(use-modules (srfi srfi-1))

(define (merge-lists a b less?)
  (cond ((null? a) b)
        ((null? b) a)
        ((less? (car b) (car a))
         (cons (car b) (merge-lists a (cdr b) less?)))
        (else
         (cons (car a) (merge-lists (cdr a) b less?)))))

(define (merge-sort lst less?)
  (if (or (null? lst) (null? (cdr lst)))
      lst
      (let ((half (quotient (length lst) 2)))
        (merge-lists (merge-sort (take lst half) less?)
                     (merge-sort (drop lst half) less?)
                     less?))))

(define words '("plum" "fig" "banana" "Cherry" "kiwi" "apple"))

(display (merge-sort '(31 4 15 9 26 5 3) >))
(newline)
(display (merge-sort words string<?))
(newline)
(display (merge-sort words string-ci<?))
(newline)
(display (merge-sort words (lambda (a b)
                             (< (string-length a) (string-length b)))))
(newline)

(define cities '(("Bratislava" . 475) ("Kosice" . 229)
                 ("Presov" . 84) ("Zilina" . 80) ("Nitra" . 76)))

(display (merge-sort cities (lambda (a b) (string<? (car a) (car b)))))
(newline)
(display (map car (merge-sort cities (lambda (a b) (< (cdr a) (cdr b))))))
(newline)

With >, the numbers come out in descending order. string<? compares character codes, so the capitalised "Cherry" comes first; string-ci<? ignores the case. A lambda sorts the words by length, and the pairs of cities and populations (in thousands) are sorted by name and by population. Merge sort keeps equal elements in their original order: "plum" and "kiwi" have the same length and stay in the input order. This is because merge-lists takes from the second list only when its element is strictly smaller.

$ guile comparator.scm
(31 26 15 9 5 4 3)
(Cherry apple banana fig kiwi plum)
(apple banana Cherry fig kiwi plum)
(fig plum kiwi apple banana Cherry)
((Bratislava . 475) (Kosice . 229) (Nitra . 76) (Presov . 84) (Zilina . 80))
(Nitra Zilina Presov Kosice Bratislava)

Counting comparisons

The three sorts can now be collected in a module, as described in the modules article. Insertion sort uses fold-right and quicksort uses partition, which returns two lists as multiple values.

sorts.scm
(define-module (sorts)
  #:use-module (srfi srfi-1)
  #:export (insertion-sort quicksort merge-sort))

(define (insert-sorted x sorted less?)
  (cond ((null? sorted) (list x))
        ((not (less? (car sorted) x)) (cons x sorted))
        (else (cons (car sorted) (insert-sorted x (cdr sorted) less?)))))

(define (insertion-sort lst less?)
  (fold-right (lambda (x sorted) (insert-sorted x sorted less?)) '() lst))

(define (quicksort lst less?)
  (if (or (null? lst) (null? (cdr lst)))
      lst
      (let ((pivot (car lst)))
        (call-with-values
            (lambda () (partition (lambda (x) (less? x pivot)) (cdr lst)))
          (lambda (smaller others)
            (append (quicksort smaller less?)
                    (list pivot)
                    (quicksort others less?)))))))

(define (merge-lists a b less?)
  (cond ((null? a) b)
        ((null? b) a)
        ((less? (car b) (car a))
         (cons (car b) (merge-lists a (cdr b) less?)))
        (else
         (cons (car a) (merge-lists (cdr a) b less?)))))

(define (merge-sort lst less?)
  (if (or (null? lst) (null? (cdr lst)))
      lst
      (let ((half (quotient (length lst) 2)))
        (merge-lists (merge-sort (take lst half) less?)
                     (merge-sort (drop lst half) less?)
                     less?))))

In insert-sorted, the test (not (less? (car sorted) x)) stops at the first element that does not have to come before x. Together with fold-right, which inserts the elements from the last to the first, equal elements keep their order.

counting.scm
(use-modules (sorts) (srfi srfi-1))

(define comparisons 0)

(define (counting-less a b)
  (set! comparisons (+ comparisons 1))
  (< a b))

(define (report name sorter data)
  (set! comparisons 0)
  (sorter data counting-less)
  (display (string-pad-right name 16))
  (display comparisons)
  (newline))

(define (try-all title data)
  (display title)
  (newline)
  (report "insertion sort" insertion-sort data)
  (report "quicksort" quicksort data)
  (report "merge sort" merge-sort data))

(define shuffled (map (lambda (i) (modulo (* i 37) 1000)) (iota 1000)))
(define ascending (iota 1000))

(display (take shuffled 8))
(newline)
(try-all "shuffled:" shuffled)
(try-all "ascending:" ascending)
(try-all "descending:" (reverse ascending))

A comparison procedure can do more than compare. counting-less counts its calls in a global variable. The program sorts a thousand numbers in three arrangements. Multiplying 0 to 999 by 37 modulo 1000 gives each number from 0 to 999 once, in a mixed order. On mixed data, merge sort makes the fewest comparisons and insertion sort the most. On data that is already sorted, insertion sort needs only one comparison per element, so it is a good choice for nearly sorted data. Quicksort with the first element as pivot degenerates on sorted input in both directions: one part is always empty, and the comparisons grow as n2/2. Merge sort stays below n log2 n, about 10,000, in all three cases.

$ guile -L . counting.scm
(0 37 74 111 148 185 222 259)
shuffled:
insertion sort  252711
quicksort       31968
merge sort      7870
ascending:
insertion sort  999
quicksort       499500
merge sort      4932
descending:
insertion sort  499500
quicksort       499500
merge sort      5044

Sorting vectors in place

The list sorts build new lists. A vector can be sorted in place: the elements are moved inside the vector, and no new vector is created. Insertion sort and selection sort are the simplest algorithms of this kind.

vectorsort.scm
(define (vector-insertion-sort! vec less?)
  (do ((i 1 (+ i 1)))
      ((>= i (vector-length vec)))
    (let ((x (vector-ref vec i)))
      (let shift ((j i))
        (if (and (> j 0) (less? x (vector-ref vec (- j 1))))
            (begin
              (vector-set! vec j (vector-ref vec (- j 1)))
              (shift (- j 1)))
            (vector-set! vec j x))))))

(define (vector-swap! vec i j)
  (let ((tmp (vector-ref vec i)))
    (vector-set! vec i (vector-ref vec j))
    (vector-set! vec j tmp)))

(define (selection-sort! vec less?)
  (let ((n (vector-length vec)))
    (do ((i 0 (+ i 1)))
        ((>= i (- n 1)))
      (let ((smallest i))
        (do ((j (+ i 1) (+ j 1)))
            ((>= j n))
          (when (less? (vector-ref vec j) (vector-ref vec smallest))
            (set! smallest j)))
        (vector-swap! vec i smallest)))))

(define scores (vector 72 95 61 88 79 95 54))
(vector-insertion-sort! scores <)
(display scores)
(newline)

(define names (vector "Tomas" "Eva" "Peter" "Anna" "Juraj"))
(selection-sort! names string<?)
(display names)
(newline)
(selection-sort! names string>?)
(display names)
(newline)

vector-insertion-sort! takes each element in turn and shifts the larger elements before it one position to the right, until the gap is where the element belongs. The do loop and the named let come from the tail calls and iteration article. selection-sort! finds the smallest remaining element and swaps it to the front of the unsorted part. The exclamation mark marks procedures that change their argument; they return nothing useful, so the programs display the vectors afterwards.

$ guile vectorsort.scm
#(54 61 72 79 88 95 95)
#(Anna Eva Juraj Peter Tomas)
#(Tomas Peter Juraj Eva Anna)

Guile's sort procedures

Guile has sorting built in. sort takes a list or a vector and a comparison procedure and returns a new sorted sequence. sort! may reuse the storage of its argument.

builtin.scm
(define temperatures (list 12 -3 25 7 18 0))

(display (sort temperatures <))
(newline)
(display temperatures)
(newline)

(define readings (vector 3.5 1.25 9.0 4.75))
(display (sort readings >))
(display " ")
(display readings)
(newline)
(sort! readings <)
(display readings)
(newline)

(define data (list 4 2 3 1))
(define sorted-data (sort! data <))
(display sorted-data)
(display " ")
(display data)
(newline)

(display (sorted? '(1 2 2 5) <))
(display " ")
(display (sorted? '(1 3 2) <))
(newline)
(display (merge '(1 4 9) '(2 3 10) <))
(newline)

sort leaves the original list and vector unchanged. sort! sorts the vector in place. With a list, sort! rearranges the pairs and returns the new first pair; the variable data still points to the pair that held 4, which is now the last pair of the sorted list. Always use the return value of sort! on a list. sorted? checks whether a sequence is in order, and merge merges two sorted lists, like merge-lists above.

$ guile builtin.scm
(-3 0 7 12 18 25)
(12 -3 25 7 18 0)
#(9.0 4.75 3.5 1.25) #(3.5 1.25 9.0 4.75)
#(1.25 3.5 4.75 9.0)
(1 2 3 4) (2 3 4)
#t #f
(1 2 3 4 9 10)

Stable sorting

A sort is stable when equal elements keep their relative order. Stability makes it possible to sort by several keys: sort by the secondary key first, then stably by the primary key. Guile's stable-sort guarantees stability; sort does not. The players are records.

stable.scm
(use-modules (srfi srfi-9))

(define-record-type <player>
  (make-player name team points)
  player?
  (name player-name)
  (team player-team)
  (points player-points))

(define players
  (list (make-player "Lucia" "red" 12) (make-player "Marek" "blue" 15)
        (make-player "Zuzana" "blue" 12) (make-player "Pavol" "red" 15)
        (make-player "Ivana" "red" 9) (make-player "Roman" "blue" 9)))

(define (show lst)
  (for-each (lambda (p)
              (display (player-name p))
              (display " ")
              (display (player-team p))
              (display " ")
              (display (player-points p))
              (newline))
            lst))

(define (by-points a b) (> (player-points a) (player-points b)))
(define (by-team a b) (string<? (player-team a) (player-team b)))

(define by-name
  (stable-sort players (lambda (a b) (string<? (player-name a) (player-name b)))))

(show (stable-sort by-name by-points))
(newline)
(show (stable-sort (stable-sort players by-points) by-team))

The first part of the output sorts the players by name and then stably by points. Players with equal points stay in alphabetical order: Marek before Pavol, Lucia before Zuzana. The second part sorts by points and then stably by team, which groups the players by team and orders each team by points. The key used in the last sort is the main key of the result.

$ guile stable.scm
Marek blue 15
Pavol red 15
Lucia red 12
Zuzana blue 12
Ivana red 9
Roman blue 9

Marek blue 15
Zuzana blue 12
Roman blue 9
Pavol red 15
Lucia red 12
Ivana red 9

Sorting by a computed key

A comparison procedure is called about n log n times, and each call computes the keys of two elements. When the key is expensive, it is better to compute it once per element, sort pairs of key and element, and drop the keys afterwards. This is known as decorate-sort-undecorate.

keys.scm
(define key-calls 0)

(define (vowel-count word)
  (set! key-calls (+ key-calls 1))
  (string-count word (char-set #\a #\e #\i #\o #\u)))

(define words
  '("strength" "education" "rhythm" "banana" "queue" "sky"
    "audio" "crypt" "sequoia" "tree" "aerie" "lynx"))

(define (sort-by-key lst key less?)
  (map cdr
       (sort (map (lambda (x) (cons (key x) x)) lst)
             (lambda (a b) (less? (car a) (car b))))))

(display (sort words (lambda (a b) (< (vowel-count a) (vowel-count b)))))
(newline)
(display "key calls: ")
(display key-calls)
(newline)

(set! key-calls 0)
(display (sort-by-key words vowel-count <))
(newline)
(display "key calls: ")
(display key-calls)
(newline)

(display (sort-by-key words string-length >))
(newline)

vowel-count counts the vowels of a word with string-count and a character set, and counts its own calls. Sorting the twelve words with a comparison that computes the counts calls it 66 times. sort-by-key pairs each word with its key, sorts the pairs by their car, and maps cdr over the result to get the words back; it calls the key procedure once per word. The last call sorts by length, longest first.

$ guile keys.scm
(rhythm sky crypt lynx strength tree banana queue audio aerie education sequoia)
key calls: 66
(rhythm sky crypt lynx strength tree banana queue audio aerie education sequoia)
key calls: 12
(education strength sequoia rhythm banana queue audio crypt aerie tree lynx sky)

Source

Sorting — GNU Guile Reference Manual

Sorting algorithm — Wikipedia

In this article we have written insertion sort, quicksort, and merge sort for lists, passed comparison procedures, counted comparisons, sorted vectors in place, used Guile's sort, sort!, sorted?, and merge, sorted stably by several keys, and sorted by a computed key. The recursion article explains the recursive procedures used here, and the vectors article covers the vector procedures.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Scheme tutorials.