Lisp - Sorting Sequence



Lisp provides sort functions which is very versatile function and can be used to sort lists, vectors etc. sort function modifies the original sequence. In case original sequence is not to be modified, then we can use copy-list to get a copy of list or copy-seq to get copy of a vector.

Syntax - sort function

sort sequence predicate &key

Arguments

  • sequence− sequence to be sorted.

  • predicate− A comparison function to compare elements of the sequence. Generally to compare numbers, < is used and to compare strings, string< is used.

  • key− An optional function which is applied on each element before comparison. Useful when sorting is to be done based on certain part of complex object.

Example - Sorting a list of numbers

Following example sorts a list of number and prints it.

main.lisp

; sort a list
(setf sortedList (sort '(4 3 7 2 1 8 3) #'<))

; print the sorted list
(print sortedList)

Output

When you execute the code, it returns the following result −

(1 2 3 3 4 7 8) 

Example - Sorting a vector of strings

Following example sorts a vector of strings and prints it.

main.lisp

; sort a vector
(setf sortedVector (sort #("D" "C" "A" "E" "F" "B") #'string<))

; print the sorted vector
(print sortedVector)

Output

When you execute the code, it returns the following result −

#("A" "B" "C" "D" "E" "F") 

Example - Sorting a list based on second element

Following example sorts a list of sublists based on the second element.

main.lisp

; create a list of sublists
(setq data '((a 3) (b 1) (c 2)))
; sort list based on second element
(setf sortedList (sort data #'< :key #'cadr))
 ; print the sorted list
(print sortedList)

Output

When you execute the code, it returns the following result −

((B 1) (C 2) (A 3)) 

Example - Sorting a list of numbers without modifying original

Following example sorts a list of number and prints it.

main.lisp

(setq numbers '(4 3 7 2 1 8 3))
; sort a list
(setf sortedList (sort (copy-list numbers) #'<))

; print the original list
(print numbers)

; print the sorted list
(print sortedList)

Output

When you execute the code, it returns the following result −

(4 3 7 2 1 8 3) 
(1 2 3 3 4 7 8)  
Advertisements