码迷,mamicode.com
首页 > 其他好文 > 详细

Merge Sort

时间:2015-11-19 20:29:44      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

 

package algorithm;

public class MergeSort
{
    public void  merge(Integer[] array, Integer begin,Integer mid ,Integer end)
    {
        Integer[] newArray = new Integer[end + 1];
        Integer sign = 0;
        while(begin <= end/2 && mid < end)
        {
            if(array[begin] < array[mid])
            {
                newArray[sign] = array[begin];
                begin++;
            }
            else
            {
                newArray[sign]= array[mid];
                mid++;
            }
            sign++;
        }
        while(begin <= end/2)
        {
            newArray[sign] = array[begin];
            begin++;
        }
        while(mid < end)
        {
            newArray[sign]= array[mid];
            mid++;
        }
        for(int i = 0; i < end; i++)
        {
            array[i] = newArray[i];
        }
    }

    public void sort(Integer[] array, Integer begin, Integer end)
    {
        if(end - begin > 0)
        {
            Integer mid = (begin + end)/2;
            sort(array,begin,mid);
            sort(array,mid,end);
           merge(array,begin,mid,end);
        }
    }
}

 

 

package altest;

import algorithm.MergeSort;

public class AlgorithmTest
{
    public static void main(String[] args)
    {
        MergeSort mergeSort = new MergeSort();
        Integer[] array ={8,2,5,4,7,0,9,1,3,6}; 
        mergeSort.sort(array,0,10);
        for(Integer i:array)
        {
            System.out.print(array [i] + " ");
        }
    }
}

 

Merge Sort

标签:

原文地址:http://www.cnblogs.com/rixiang/p/4978454.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!