Scala Practice-merge sort

Source: Internet
Author: User
Tags sort

Source
Merge sort

Package DAY14 Import Scala.collection.mutable.ArrayBuffer/** * Created by Doctorq on 2017/6/26.  * Merge Sort */object MergeSort extends App {/** * 2 sequential array merges, O (n) Time complexity * * @param left * @param right * @return */def mergearray (Left:arraybuffer[int], Right:arraybuffer[int]): Arraybuffer[int] = {val Sortedarra y = new Arraybuffer[int] () while (left.size! = 0 && Right.size! = 0) {val Leftitem = Left.head V 
      Al Rightitem = Right.head if (Leftitem < Rightitem) {sortedarray.append (leftitem) left.remove (0)
      } else {sortedarray.append (rightitem) right.remove (0)}} if (Left.size! = 0) {
  Sortedarray.appendall (left)} else if (right.size! = 0) {Sortedarray.appendall (right)} Sortedarray } def mergesort (List:arraybuffer[int]): arraybuffer[int] = {if (list.size <= 1) return list var left = Arraybuffer[int] () var right = ArraybufFer[int] () val size = List.size for (i <-0 until size) {if (I < SIZE/2) {Left.append (list
    (i))} else {right.append (list (i)}}} left = MergeSort (left) right = MergeSort (right) Mergearray (left, right)} def printlnlist (Sortedheap:arraybuffer[int]): Unit = {Sortedheap.foreach (item =&gt ;

  Print (S "$item")) println ("sorted!")} Val list = ArrayBuffer (4, 3, 23°c, 5, 6, 7,, 6, 7, 3, 5, 7, 8, 3, 4, 6, 8, 3, 5, 7) Val sortedList = MergeSort (lis
 T) printlnlist (SortedList)}

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.