summary refs log tree commit diff stats
path: root/tests/compile/tsortdev.nim
blob: 1b7705d8126689c26084c9ca694f5c16173870f7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
discard """
  disabled: false
"""

import math, algorithm

proc sorted[T](a: openArray[T], order: TSortOrder): bool = 
  result = true
  for i in 0 .. < a.high:
    if cmp(a[i], a[i+1]) * order > 0: 
      echo "Out of order: ", a[i], " ", a[i+1]
      result = false

proc bubbleSort[T](a: var openArray[T], 
                   cmp: proc (x, y: T): int,
                   order = TSortOrder.Ascending) =
  while true:
    var sorted = true
    for i in 0 .. a.len-2:
      if cmp(a[i], a[i+1]) * order > 0:
        swap(a[i], a[i+1])
        sorted = false
    if sorted: break

when isMainModule:
  proc main() =
    const order = Ascending
    var data: seq[string] = @[]
    
    var L = random(59)
    for i in 0..2:
      #echo "loop: ", i
      #newSeq(data, L)
      setLen(data, L)
      for j in 0 .. L-1:
        data[j] = $(math.random(90) - 10)
        assert getRefcount(data[j]) == 1
        {.watchpoint: data.}
      var copy = data
      for j in 0 .. L-1:
        assert getRefcount(copy[j]) == 1
        assert(cast[pointer](copy[j]) != cast[pointer](data[j]))
      
      bubblesort(data, system.cmp, order)
      if not sorted(data, order):
        quit "bubblesort failed"

      sort(copy, cmp, order)
      for j in 0 .. L-1:
        let rc = getRefcount(data[j])
        if rc != 1:
          echo "RC IST ", rc, " j: ", j
          assert getRefcount(data[j]) == 1
    when false:
      if copy.len != data.len: 
        quit "lengths differ!"
      for i in 0 .. copy.high:
        if copy[i] != data[i]:
          quit "algorithms differ!"
    when false:
      for i in 0..10_000:
        var data: seq[int]
        var L = random(59)
        newSeq(data, L)
        for j in 0 .. L-1: 
          data[j] = (math.random(90) - 10)
        var copy = data
        sort(data, cmp[int], order)
        if not sorted(data, order):
          quit "sort for seq[int] failed"
        bubblesort(copy, system.cmp[int], order)
        if copy.len != data.len: 
          quit "lengths differ!"
        for i in 0 .. copy.high:
          if copy[i] != data[i]:
            quit "algorithms differ!"

  main()

echo "done"