JAVA下的归并排序

来源:互联网 发布:再度重相逢dj网络歌手 编辑:程序博客网 时间:2024/06/14 09:15

JAVA下的归并排序代码(测试过的):

(原理我就不贴了,百度一下大把)

/* * Created by Linyue on 2014/4/25. */class Sort{    public static <T extends Comparable>void mergeSort(T[] a,int first,int last){        T[] temp;        temp = (T[])new Comparable[a.length];        callMergeSort(a,temp,first,last);    }    public static  <T extends Comparable> void callMergeSort(T[] a,T[] temp,int first,int last){        if (first < last) {            int mid = (first+last)/2;            callMergeSort(a,temp,first,mid);            callMergeSort(a,temp,mid+1,last);            merge(a,temp,first,mid,last);        }    }    private static <T extends Comparable> void merge(T[] a,T[] temp,int first,int mid,int last){        int beginHalf1=first;        int beginHalf2=mid+1;        int index=0;        while(beginHalf1<= mid &&beginHalf2<= last){            if (a[beginHalf1].compareTo(a[beginHalf2])<=0) {                temp[index]=a[beginHalf1];                beginHalf1++;            }else{                temp[index]=a[beginHalf2];                beginHalf2++;            }            index++;        }        while(beginHalf1<= mid){            temp[index]=a[beginHalf1];            index++;            beginHalf1++;           //把第一个数组剩下的数字复制完        }        while (beginHalf2<= last){            temp[index]=a[beginHalf2];            index++;            beginHalf2++;           //把第二个数组剩下的数字复制完        }        System.arraycopy(temp,0,a,first,last-first+1);//使用System里的方法,IDEA推荐的,貌似使用C写的,可能效率高一点。        /*for (int i=first;i<=last;i++){            a[i]=temp[i-first];     //注意要把temp里的元素复制回原来的数组里面        }*/    }}public class main {    public static void main(String[] args) {        Integer[] a={1,3,5,4,6,7,2};        Sort.mergeSort(a,0,a.length-1);        for (Integer i :a) {            System.out.println(i);        }    }}



0 0
原创粉丝点击