summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorAndreas Rumpf <rumpf_a@web.de>2015-06-20 02:55:46 +0200
committerAndreas Rumpf <rumpf_a@web.de>2015-06-20 02:55:46 +0200
commit54045b785b22ec9a3c8312d401f34ae6e9e54498 (patch)
tree8876c6d28112ca33ed48c64a746a88394ff34b17
parent717db99fb687d8548bf4fa2069be3ccf441bd34d (diff)
parentdc41beed5a00db02b8d4accf40916b5684df3c3b (diff)
downloadNim-54045b785b22ec9a3c8312d401f34ae6e9e54498.tar.gz
Merge pull request #2951 from apense/patch-5
Added `isSorted` proc
-rw-r--r--lib/pure/algorithm.nim21
1 files changed, 21 insertions, 0 deletions
diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim
index c9f779018..ac18ae420 100644
--- a/lib/pure/algorithm.nim
+++ b/lib/pure/algorithm.nim
@@ -237,6 +237,17 @@ template sortedByIt*(seq1, op: expr): expr =
     result = cmp(a, b))
   result
 
+proc isSorted*[T](a: openarray[T],
+                 cmp: proc(x, y: T): int {.closure.},
+                 order = SortOrder.Ascending): bool =
+  ## Checks to see whether `a` is already sorted in `order`
+  ## using `cmp` for the comparison. Parameters identical
+  ## to `sort`
+  result = true
+  for i in 0..<len(a)-1:
+    if cmp(a[i],a[i+1]) * order > 0:
+      return false
+
 proc product*[T](x: openArray[seq[T]]): seq[seq[T]] =
   ## produces the Cartesian product of the array. Warning: complexity
   ## may explode.
@@ -340,4 +351,14 @@ when isMainModule:
   assert arr.lowerBound(4) == 1
   assert arr.lowerBound(5) == 1
   assert arr.lowerBound(6) == 2
+  # Tests for isSorted
+  var srt1 = [1,2,3,4,4,4,4,5]
+  var srt2 = ["iello","hello"]
+  var srt3 = [1.0,1.0,1.0]
+  var srt4 = []
+  assert srt1.isSorted(cmp) == true
+  assert srt2.isSorted(cmp) == false
+  assert srt3.isSorted(cmp) == true
+  var srtseq = newSeq[int]()
+  assert srtseq.isSorted(cmp) == true