Skip to content

Functional way to write Sorting algorithm #79

Description

@Manupendra

I can see the imperative code in sorting algorithm, I'm intending to add in functional way
for e.g. In MergeSort , I can see while loop which is an iterative approach -

while (k < high + 1) {
        // must check if empty to avoid exceptions
        if (i > left.length - 1) {
          array(k) = right(j)
          j = j + 1
        } else if (j > right.length - 1) {
          array(k) = left(i)
          i = i + 1
        } else if (left(i) <= right(j)) {
          array(k) = left(i)
          i = i + 1
        } else {
          array(k) = right(j)
          j = j + 1
        }
        k = k + 1
      }

Best Practice: In scala, we follow functional way to write it

def merge(xs: List[Int], ys: List[Int]): List[Int] = (xs, ys) match {
    // If either list is empty, return the other list
    case (Nil, _) => ys
    case (_, Nil) => xs
    // If the first element of xs is smaller than the first element of ys,
    // append it to the result of merging the rest of xs with ys
    case (x :: xtail, y :: ytail) =>
      if (x < y) x :: merge(xtail, ys)
      // Otherwise, append the first element of ys to the result of merging xs with the rest of ys
      else y :: merge(xs, ytail)
  }

I'll be creating a PR shortly to add functional code for sorting algorithm given in this repo.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions