Lisp - Sorting List



Lisp provides sort functions which is very versatile function and can be used to sort lists easilty. 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.

Syntax - sort function

sort list predicate &key

Arguments

  • sequence− list to be sorted.

  • predicate− A comparison function to compare elements of the list. 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 list of strings

Following example sorts a list of strings and prints it.

main.lisp

; sort a list
(setf sortedList (sort '("Apple" "Coconut" "Banana" "Orange" "Manago") #'string<))

; print the sorted list
(print sortedList)

Output

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

("Apple" "Banana" "Coconut" "Manago" "Orange") 

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