"Scala Programming" functional style-writing sorting algorithm

Source: Internet
Author: User

About Scala Programming examples

At the beginning of learning a programming language, always want to write some relatively large programs and projects, but because the foundation is not solid, often make haste. So, only one step at a time, through some classic small examples to practice and exercise, and eventually continue to deepen the skills of programming, adhere to, believe that slowly become proficient.

General notation for bubble sort, select sort, insert sort

There are not so many things to say about these three sorting methods, and there is no difference between the programming and the specified style.
The array data is used here because the array array is a mutable sequence of objects whose element values can be changed, and the elements of the list class object are immutable.
The notation here is not a functional style, where VAR variables are used, and each function has side effects, because these functions change the contents of the input array.

  defBubblesort (Arr:array[int]): Unit = { for(I <-0Until arr.length-1; J <-0Until arr.length-1-I.) {if(arr (j) > Arr (j+1)){ValTMP = arr (j) Arr (j) = arr (j+1) Arr (j+1) = tmp}}}defSelectsort (Arr:array[int]): Unit = { for(I <-0Until arr.length-1){varMin_ind = i for(J <-i+1To arr.length-1) {if(Arr (j) < arr (min_ind)) {min_ind = j}}if(Min_ind! = i) {ValTMP = arr (i) arr (i) = arr (min_ind) arr (min_ind) = tmp}}}defInsertsort (Arr:array[int]): Unit = { for(I <-1Until Arr.length) {ValTMP = arr (i)varj = I1       while(J >-1&& arr (j) > tmp) {arr (j+1) = Arr (j) J-=1} arr (j+1) = tmp}}
Insert ordering based on pattern matching

The Insertsort function uses pattern matching as a split list, inserting the left-most separated elements into the order in which they are placed, and using recursive calls to continuously split the list.
In the style of instruction, use a loop to remove the leftmost element in turn, and then insert it in a sequential position from the left. In this way, a recursive functional approach is used to first split the list recursively and then insert them sequentially. The recursive approach is simple in structure, but not easy to understand.

  defmatch  {    case List() => List()    case x :: xs1 => insert(x, insertSort(xs1))  }  defmatch {    case List() => List(x)    case y :: ys =>      if (x <= y) x :: xs      else y :: insert(x, ys)  }
Merge sort

How merge sorting works: First, if the list length is zero or only one element, it is already sorted, so it can be returned without change. A long list can be split into two sub-lists, each containing about half of the original list elements. Each sub-list takes a recursive call to the permutation function to complete the sort, and then merges the resulting list of two sorted lists together with a merge operation.

Here, we'll post the code and explain:

def  merge (a:list[ INT], B:list[int]): list[int] = (A, b) match  {case  (Nil, _) = B case  (_, nil) = a case  (X::xs, Y::ys) = if  (x <= y) x:: Merge (XS, b) el Se  y:: Merge (A, Ys)}def  mergesort (Lst:list[int]): list[int] = {if  (Lst.length < 2 ) lst else  {val  (first, second) = Lst.splitat (Lst.length/2 ) Merge (MergeSort (first), MergeSort (second))}}  

In the MergeSort function, the sub-sequences are recursively segmented using the divide-and-conquer strategy, and then the continuously segmented sub-sequences are merged from the bottom up; in the merge function, two sub-sequences are combined by pattern matching in the (x::xs, y::ys) corresponding mode, infix operator :: is treated as a constructor pattern (in fact, there is a class named, scala.:: which can create a non-empty list), so that the list is split, sorted by the size of the element and merged. In addition, the merge function uses tail recursion to optimize performance.

The following is a more functional style of writing:
This can be done with functions within the function, which is better overall. For a general implementation of a merge sort, you may want to make no restrictions on the type of list element to be sorted, and you want to make no restrictions on the functions used to compare the elements. The types are generalized by type parameterization, and a comparison function is added as a parameter by using the method of curry.

 def  Msort[t] (less: (t, t) = = Boolean) (Xs:list[t]): list[t] = {def  merge (Xs:list[t], ys:list[t]): list[t] = (xs , ys) match  {case  (Nil, _) = Ys  case (_, Nil) = xs case  (x:: XS1, Y:: ys1) = > if  (less (x, y)) x:: Merge (XS1, ys) els E  y:: Merge (XS, ys1)} val  n = xs.length/ 2  if  (n = = 0 ) xs e LSE  {val  (ys, ZS) = xs splitat n merge (Msort (less) (YS), Msort (less) (ZS )) } }} 
Quick Sort

Quick ordering of prescriptive styles:

  defQsort (Xs:array[int]): Unit = {defSwap (I:int, j:int): Unit = {Valt = xs (i); XS (i) = XS (j); XS (j) = T}defSort1 (L:int, r:int): Unit = {ValPivot = XS ((l+r)/2)vari = l;varj = R while(I <= J) { while(XS (i) < pivot) I + =1         while(XS (j) > Pivot) J-=1        if(I <= J) {Swap (I, j) i + =1J-=1}      }if(L < J) Sort1 (L, J)if(J < R) Sort1 (I, R)} sort1 (0, xs.length-1)  }}

Quick ordering of functional styles:

  def quickSort(xs: Array[Int]): Array[Int] = {    if1) xs    else{      val2)      Array.concat(        quickSort(xs filter (pivot >)),                  xs filter (pivot ==),        quickSort(xs filter (pivot <))      )    }  }

A more concise quick sort:

def quickSort(lst: List[Int]): List[Int] = {    val p = lst.head    val (before, after) = lst.tail.partition(_ < p)    quickSort(before) ++ (p :: quickSort(after))}

reprint Please indicate the author Jason Ding and its provenance
Gitcafe Blog Home page (http://jasonding1354.gitcafe.io/)
GitHub Blog Home page (http://jasonding1354.github.io/)
CSDN Blog (http://blog.csdn.net/jasonding1354)
Jane Book homepage (http://www.jianshu.com/users/2bd9b48f6ea8/latest_articles)
Google search jasonding1354 go to my blog homepage

"Scala Programming" functional style-writing sorting algorithm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.