Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add merge to algoirithm #7

Open
ringabout opened this issue Nov 29, 2020 · 1 comment
Open

add merge to algoirithm #7

ringabout opened this issue Nov 29, 2020 · 1 comment

Comments

@ringabout
Copy link
Owner

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
Copy link
Owner Author

ringabout commented Nov 29, 2020

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant