"Fundamentals of Algorithmic Design and analysis" 13, merge sort

Source: Internet
Author: User

Tag:print   ima    Traversal    copy   com    get    first    lis   data   

Package Cn.xf.algorithm.ch04;import Java.util.arraylist;import Java.util.arrays;import java.util.List;import Org.junit.test;public class MergeSort {public void Msort (list<integer> data) {if (Data.size () <= 1) {return;} Copy both sides of the data list copya = new ArrayList (); List Copyb = new ArrayList (); for (int i = 0; i < data.size ()/2; ++i) {Copya.add (Data.get (i));} for (int j = data.size ()/2; J < Data.size (); ++j) {Copyb.add (Data.get (j));} Recursive sorted subset Msort (COPYA); Msort (COPYB);//after sorting, put back data in merge (Copya, COPYB, data);} /** * Merge two subsets * @param dataa * @param datab * @param data */public void merge (List<integer> dataa, List<integer&gt ; Datab, List data) {//traverse a,b,dataint i = 0, j = 0, k = 0;while (i < Dataa.size () && J < Datab.size ()) {//Traverse both sides Data if (Dataa.get (i) <= Datab.get (j)) {//bar A is put in Data.set (K, Dataa.get (i++));} else {Data.set (k, Datab.get (j + +));} K + = 1;} if (I >= dataa.size ()) {//If the first one is last, then copy the back of B into for (; J < Datab.size (); ++j) {Data.set (k++, Datab.get (j));}} else {for (; I < dataa.size (); ++i) {Data.set (k++, Dataa.get (i));}}} @Testpublic void Test1 () {list<integer> data = Arrays.aslist (8,3,2,9,7,1,5,4);//Sort MergeSort ms = new MergeSort () ; Ms.msort (data); for (int i:data) {System.out.print (i + "");}}}

  

Results:

"Fundamentals of Algorithmic Design and analysis" 13, merge sort

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.