码迷,mamicode.com
首页 > 编程语言 > 详细

归并排序

时间:2016-02-15 22:37:40      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

package cn.aust.zyw.demo;

/**
 * Created by zyw on 2016/2/15.
 */
public class MergeSort2 {
    public static void main(String args[]){
        int a[]={3,2,5,6,1,7,4};
        mergeSort(a);
        for(int i=0;i<a.length;i++){System.out.print(a[i]+" ");}
    }
    public static void mergeSort(int[] array) {
        sortArray(array, 0, array.length - 1);
    }
    //merge合并
    public static void merge(int a[],int low,int mid,int high){
        int i=low;
        int m=mid+1;
        int k=0;
        int temp[]=new int[high-low+1];
        while(i<=mid&&m<=high){
            if(a[i]>a[m]){
                temp[k++]=a[m++];
            }else{
                temp[k++]=a[i++];
            }
        }
while (i<=mid){ temp[k++]=a[i++]; } while (m<=high){ temp[k++]=a[m++]; } for(k=0,i=low;i<=high;i++,k++){ a[i]=temp[k]; } } //sortArray分组 public static void sortArray(int[] array, int start, int end) { if (start == end) { return; } int sortSize = end - start + 1; int seperate; if (sortSize % 2 == 0) { seperate = start + sortSize / 2 - 1; } else { seperate = start + sortSize / 2; } sortArray(array, start, seperate); sortArray(array, seperate + 1, end); merge(array, start, seperate, end); } }

 

归并排序

标签:

原文地址:http://www.cnblogs.com/yunwuzhan/p/5191420.html

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