Ruby Implementation of Merge Sorting

Source: Internet
Author: User

AlgorithmCourse assignments are sorted by merge using the division and Control Law.

# Encoding: UTF-8 # Author: Xu Jin, 4100213 # Date: Oct 27,201 2 # mergesort # To sort an array by using mergesort algorithm # example output: # The original array is: [4, 32, 84, 58, 49, 40, 75, 29, 82, 21, 70, 37, 70] # The sorted array is: [4, 21, 29, 32, 37, 40, 49, 58, 70, 70, 75, 82, 84] Max = 100 arrayint = array. newfor index in (0 .. 12) arrayint [Index] = rand (100) # produce 12 random numberendputs "The origina L array is: "+ arrayint. to_sdef merge (ARR, left, middle, right) arrl, Arrr = array. new, array. new arrl [0 .. (middle-left)], Arrr [0 .. (right-middle-1)] = arr [left .. middle], arr [Middle + 1 .. right] arrl [arrl. size], Arrr [Arrr. size] = max, Max for K in (left .. right) arrl. first <= Arrr. first? (ARR [k] = arrl. shift): (ARR [k] = Arrr. shift) endenddef merge_sort (ARR, left, right) if left <right then middle = (left + right)/2 merge_sort (ARR, left, middle) merge_sort (ARR, middle + 1, right) Merge (ARR, left, middle, right) endendmerge_sort (arrayint, 0, arrayint. length-1) puts "the sorted array is:" + arrayint. to_s
Related Article

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.