Example code of bubble sort, merge sort and fast sort in Scala

Time:2019-10-19

1. Bubble sorting


def sort(list: List[Int]): List[Int] = list match {
  case List() => List()
  case head :: tail => compute(head, sort(tail))
 }

 def compute(data: Int, dataSet: List[Int]): List[Int] = dataSet match {
  case List() => List(data)
  case head :: tail => if (data <= head) data :: dataSet else head :: compute(data, tail)
 }

def main(args: Array[String]) {
  val list = List(3, 12, 43, 23, 7, 1, 2, 0)
  println(sort(list))
 }

2. Merge and sort


def mergedSort[T](less: (T, T) => Boolean)(list: List[T]): List[T] = {

  def merged(xList: List[T], yList: List[T]): List[T] = {
   (xList, yList) match {
    case (Nil, _) => yList
    case (_, Nil) => xList
    case (x :: xTail, y :: yTail) => {
     if (less(x, y)) x :: merged(xTail, yList)
     else
      y :: merged(xList, yTail)
    }
   }
  }

  val n = list.length / 2
  if (n == 0) list
  else {
   val (x, y) = list splitAt n
   merged(mergedSort(less)(x), mergedSort(less)(y))
  }
 }

def main(args: Array[String]) {
  val list = List(3, 12, 43, 23, 7, 1, 2, 0)
  println(mergedSort((x: Int, y: Int) => x < y)(list))
 }

3. Quick sorting


 def quickSort(list: List[Int]): List[Int] = {
  list match {
   case Nil => Nil
   case List() => List()
   case head :: tail =>
    val (left, right) = tail.partition(_ < head)
    quickSort(left) ::: head :: quickSort(right)
  }
 }

def main(args: Array[String]) {
  val list = List(3, 12, 43, 23, 7, 1, 2, 0)
  println(quickSort(list))
 }

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.

Recommended Today

How to check the package according to the command in CentOS

In our work, we often encounter that we want to use a command machine that is not installed, but we don’t know which package the command is in (source compilation is not covered in this article). Here is a rather stupid method to help us solve this problem. Explain:Blue = command name Light green = […]