quicksort.nim 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import os
  2. import strutils
  3. # Generate some pseudo-random data
  4. var seed: tuple[s1, s2, s3: int32] = (2'i32, 8'i32, 16'i32)
  5. proc random(): int32 =
  6. seed = (((((((seed[0] and 0x0007_FFFF'i32) shl 13'i32) xor seed[0]) shr
  7. 19'i32) and 0x0000_1FFF'i32) xor
  8. ((seed[0] and 0x000F_FFFE'i32) shl 12'i32)),
  9. ((((((seed[1] and 0x3FFF_FFFF'i32) shl 2'i32) xor seed[1]) shr
  10. 25'i32) and 0x0000_007F'i32) xor
  11. ((seed[1] and 0x0FFF_FFF8'i32) shl 4'i32)),
  12. ((((((seed[2] and 0x1FFF_FFFF'i32) shl 3'i32) xor seed[2]) shr
  13. 11'i32) and 0x001F_FFFF'i32) xor
  14. ((seed[2] and 0x0000_7FF0'i32) shl 17'i32)))
  15. return seed[0] xor seed[1] xor seed[2]
  16. var n = 9999999
  17. var data: seq[int32]
  18. newSeq (data, n)
  19. for i in 0 .. data.high():
  20. data[i] = random()
  21. proc `$` (d: seq[int32]): string =
  22. result = "[ "
  23. for i in items (d):
  24. result.addSep (", ", 2)
  25. result.add ($(i and 0xFFFF_FFFF'i64))
  26. result.add (" ]")
  27. # Sort the data
  28. proc sort (start, stop: int) =
  29. if stop <= start+1:
  30. return
  31. var j = start
  32. for i in start..stop-2:
  33. if data[i] <% data[stop-1]:
  34. swap (data[i], data[j])
  35. inc (j)
  36. swap (data[j], data[stop-1])
  37. sort (start, j)
  38. sort (j+1, stop)
  39. sort (0, data.len)
  40. echo (data[n div 2 - 1] and 0xFFFF_FFFF'i64, ", ",
  41. data[n div 2] and 0xFFFF_FFFF'i64, ", ",
  42. data[n div 2 + 1] and 0xFFFF_FFFF'i64)