algorithm
nimony/lib/std/algorithm.nim
type SortOrder = enum Descending = (0, "Descending") Ascending = (1, "Ascending")
func dollar`.SortOrder(e: SortOrder): stringfunc *(x: int64; order: SortOrder): int64Flips the sign of
xiforder == Descending. Iforder == Ascendingthenxis returned.xis supposed to be the result of a comparator, i.e.|
< 0for less than,|
== 0for equal,|
> 0for greater than.proc sort(a: var openArray[T]; cmp: proc (x: T, y: T): int64; order: SortOrder)Default Nim sort (an implementation of merge sort). The sorting is guaranteed to be stable (that is, equal elements stay in the same order) and the worst case is guaranteed to be O(n log n). Sorts by
cmpin the specifiedorder.The current implementation uses an iterative mergesort to achieve this. It uses a temporary sequence of length
a.len div 2. If you do not wish to provide your owncmp, you may usesystem.cmpor instead call the overloaded version ofsort, which usessystem.cmp.nim sort(myIntArray, system.cmp[int]) # do not use cmp[string] here as we want to use the specialized # overload: sort(myStrArray, system.cmp)You can inline adhoc comparison procs with the do notation. Example:
nim people.sort do (x, y: Person) -> int: result = cmp(x.surname, y.surname) if result == 0: result = cmp(x.name, y.name)See also:
sort proc<#sort,openArray[T]>_sorted proc<#sorted,openArray[T],proc(T,T)>_ sorted bycmpin the specified ordersorted proc<#sorted,openArray[T]>_sortedByIt template<#sortedByIt.t,untyped,untyped>_
proc sorted(a: openArray[T]; cmp: proc (x: T, y: T): int64; order: SortOrder): seq[T]Returns
asorted bycmpin the specifiedorder.See also:
sort func<#sort,openArray[T],proc(T,T)>_sort proc<#sort,openArray[T]>_sortedByIt template<#sortedByIt.t,untyped,untyped>_
proc isSorted(a: openArray[T]; cmp: proc (x: T, y: T): int64; order: SortOrder): boolChecks to see whether
ais already sorted inorderusingcmpfor the comparison. The parameters are identical tosort. Requires O(n) time.See also:
isSorted proc<#isSorted,openArray[T]>_