简体   繁体   中英

How to implement Insertion Sort in Scala?

I have the following code given in Scala:

def insertsort (l: List[Int]): List[Int] = {
        if (l == Nil) Nil
        else insert (l.head, insertsort (l.tail))
}

How do I implement insert() now?

Here's how I'd go about insertion sort:

def insertSort(l: List[Int]): List[Int] = {
  l.foldLeft(List.empty[Int]) { (sorted, i) =>
    val (less, greater) = sorted.partition(_ < i)
    (less :+ i) ++ greater
  }
}

If you're not familiar with foldLeft, here's how it works. When we say l.foldLeft, that means we're going to do something for each member of l, the list we want to sort. We pass in as the first argument an empty list, which represents the portion of the list we have already sorted (which starts empty because we haven't done anything yet). For each iteration of the foldLeft, we are going to add one more element of the list in sorted order, and build upon our solution this way.

The second argument is a function with two arguments. The first is the accumulating sorted list, the second is the current integer from l that we are attempting to add into the sorted list. We split the sorted list into two lists, one that is less than the current int, and one that is greater than/equal. we then insert our int in the middle. The return value of this function becomes the first argument in the next iteration (what we called 'sorted').

Let's sort l = List(3, 1, 2)

1st pass: sorted = Nil, i = 3. less and greater are both Nil. the function returns Nil + 3 + Nil, which is List(3), which becomes sorted for the next pass.

2nd pass: sorted = List(3), i = 1. less = Nil, greater = List(3). the function returns Nil + 1 + List(3), which = List(1, 3).

3rd pass: sorted = List(1, 3), i = 2. less = List(1), greater = List(3). function returns List(1) + 2 + List(3) = List(1, 2, 3).

After we have iterated over all of l, the foldLeft returns the final accumulated value (the value of the last line of the last iteration, in our case: List(1, 2, 3)).

Hope that helps!

Check this out.

/**
   * Insertion sort algorithm(https://en.wikipedia.org/wiki/Insertion_sort)
   * typically has nested loops with mutable state in imperative style of program
   *
   * Steps of an insertion sort:
   * 3 7 4 9 5 2 6 1
   * 3 7 4 9 5 2 6 1
   * 3 7 4 9 5 2 6 1
   * 3 4 7 9 5 2 6 1
   * 3 4 7 9 5 2 6 1
   * 3 4 5 7 9 2 6 1
   * 2 3 4 5 7 9 6 1
   * 2 3 4 5 6 7 9 1
   * 1 2 3 4 5 6 7 9
   *
   * @param input
   * @return
   */
  def insertionSort(input: List[Int]): List[Int] = {

    input.foldLeft(List[Int]())( (acc, element) => {

      val (firstHalf, secondHalf) = acc.span(_ < element)

      //inserting the element at the right place
      firstHalf ::: element :: secondHalf
    })
  }

Here is the source code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM