JAVA实现归并排序

package tree;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by rightHead on 2017/3/6.
 */
public abstract class MergeSort<T> {

    private T[] result;
    public abstract boolean compare(T arg1, T arg2);

    public void sort(T[] s, int start, int end) {
        result = s;
        Sort(start, end);
    }

    private void Sort(int start, int end) {
        if (start >= end){
            return;
        }
        T[] cache = result;
        List<T> group1 = new ArrayList<>();
        List<T> group2 = new ArrayList<>();
        int group1Start, group1End, group2Start, group2End;
        if (end - start == 1){
            group1Start = group1End = start;
            group2Start = group2End = end;
        }else{
            int temp = (start+end) >> 1;
            group1Start = start;
            group1End = temp;
            group2Start = temp+1;
            group2End = end;
        }
        for (int i=group1Start; i<=group1End; i++){
            group1.add(cache[i]);
        }
        Sort(group1Start, group1End);
        group1.removeAll(group1); // 这个方法的效率未知
        for (int i=group1Start; i<=group1End; i++){
            group1.add(cache[i]);
        }
        for (int i=group2Start; i<=group2End; i++){
            group2.add(cache[i]);
        }
        Sort(group2Start, group2End);
        group2.removeAll(group2);
        for (int i=group2Start; i<=group2End; i++){
            group2.add(cache[i]);
        }
        int i=0,j=0,k=start;
        int group1Size = group1.size();
        int group2Size = group2.size();
        while (true){
            if (compare(group1.get(i), group2.get(j))){
                cache[k++] = group1.get(i++);
            }else{
                cache[k++] = group2.get(j++);
            }

            if (i == group1Size){
                while (j != group2Size){
                    cache[k++] = group2.get(j++);
                }
                return;
            }
            if (j == group2Size){
                while (i != group1Size){
                    cache[k++] = group1.get(i++);
                }
                return;
            }
        }
    }
}
    public static void main(String[] args) {

        MergeSort<Integer> mergeSort = new MergeSort<Integer>() {
            @Override
            public boolean compare(Integer arg1, Integer arg2) {
                return arg1 > arg2;
            }
        };
        Integer[] xo = {8,4,7,5,9,2,1,3,0};
        mergeSort.sort(xo, 0, xo.length-1);
        for (int s : xo){
            System.out.println(s);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值