ringabout / Nim

Nim is a statically typed compiled systems programming language. It combines successful concepts from mature languages like Python, Ada and Modula. Its design focuses on efficiency, expressiveness, and elegance (in that order of priority).
https://nim-lang.org
Other
1 stars 0 forks source link

add merge to algoirithm #7

Open ringabout opened 4 years ago

ringabout commented 4 years ago

Merge two sorted array

Function Prototype:

proc merge[T](x, y: openArray[T], cmp: proc(x, y: T): int {.closure.}, order = SortOrder.Ascending): seq[T]

C++ (merge algorithm): http://www.cplusplus.com/reference/algorithm/merge

D: https://dlang.org/library/std/algorithm/sorting/merge.html

Python(based on heap) https://docs.python.org/3/library/heapq.html#heapq.merge

ringabout commented 4 years ago

Implementation:

import algorithm

proc merge*[T](x, y: openArray[T], cmp: proc(x, y: T): int {.closure.}, order = SortOrder.Ascending): seq[T] =
  ## Merges two sorted `openArray`. All of inputs are assumed to be sorted.
  ## If you do not wish to provide your own ``cmp``,
  ## you may use `system.cmp` or instead call the overloaded
  ## version of `merge`, which uses `system.cmp`.
  ##
  ## **See also:**
  ## * `merge proc<#merge,openArray[T],openArray[T]>`_
  runnableExamples:
    import algorithm
    let x = @[1, 3, 6]
    let y = @[2, 3, 4]

    let res = x.merge(y, system.cmp[int])
    assert res.isSorted
    assert res == @[1, 2, 3, 3, 4, 6]
  let
    size_x = x.len
    size_y = y.len

  result = newSeqOfCap[T](size_x + size_y)
  var
    index_x = 0
    index_y = 0
  while true:
    if index_x == size_x:
      result.add y[index_y .. ^1]
      return

    if index_y == size_y:
      result.add x[index_x .. ^1]
      return

    let item_x = x[index_x]
    let item_y = y[index_y]

    if cmp(item_x, item_y) * order > 0:
      result.add item_y
      inc index_y
    else:
      result.add item_x
      inc index_x