From d9687b5546d8b01092baa66375c094ec28b26fd8 Mon Sep 17 00:00:00 2001 From: Maria Scott Date: Tue, 9 Jan 2024 15:22:09 +0100 Subject: [PATCH] Improve list comprehensions quicksort example MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Björn Gustavsson --- .../list_comprehensions.xml | 47 ++++++++++++++----- 1 file changed, 34 insertions(+), 13 deletions(-) diff --git a/system/doc/programming_examples/list_comprehensions.xml b/system/doc/programming_examples/list_comprehensions.xml index 25df0a06bc7e..cf1b4aadd936 100644 --- a/system/doc/programming_examples/list_comprehensions.xml +++ b/system/doc/programming_examples/list_comprehensions.xml @@ -56,26 +56,47 @@ Quick Sort

The well-known quick sort routine can be written as follows:

[]; +sort([_] = L) -> L; sort([Pivot|T]) -> sort([ X || X <- T, X < Pivot]) ++ [Pivot] ++ - sort([ X || X <- T, X >= Pivot]); -sort([]) -> [].]]> + sort([ X || X <- T, X >= Pivot]).]]>

The expression is the list of all elements in T that are less than Pivot.

= Pivot]]]> is the list of all elements in T that are greater than or equal to Pivot.

-

A list sorted as follows:

- - The first element in the list is isolated - and the list is split into two sublists. - The first sublist contains - all elements that are smaller than the first element in - the list. - The second sublist contains all elements that are greater - than, or equal to, the first element in the list. - Then the sublists are sorted and the results are combined. - +

With the algorithm above, a list is sorted as follows:

+ + A list with zero or one element is trivially sorted. + For lists with more than one element: + + The first element in the list is isolated as the pivot element. + The remaining list is partitioned into two sublists, such that: + + The first sublist contains all elements that are smaller + than the pivot element. + The second sublist contains all elements that are greater + than or equal to the pivot element. + + + The sublists are recursively sorted by the same algorithm + and the results are combined, resulting in a list consisting of: + + All elements from the first sublist, that is all elements + smaller than the pivot element, in sorted order. + The pivot element. + All elements from the second sublist, that is all elements + greater than or equal to the pivot element, in sorted order. + + + + + +

While the sorting algorithm as shown above serves as a nice example to illustrate + list comprehensions with filters, for real world use cases the + lists module contains sorting functions + that are implemented in a more efficient way.