首页 > 代码库 > 归并排序

归并排序

java实现

package sort;public class MergeSort {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub                int[] arr={16,7,3,20,17,8};                int[] result=mergeSort(arr);                for(int i=0; i<result.length; i++)            System.out.print(result[i]+" ");    }    private static int[] mergeSort(int[] arr) {        // TODO Auto-generated method stub                if(arr.length==1)            return arr;                int half=arr.length/2;        int[] a=new int[half];        int[] b=new int[arr.length-half];                System.arraycopy(arr, 0, a, 0, half);        System.arraycopy(arr, half, b, 0, b.length);        a=mergeSort(a);        b=mergeSort(b);                return mergeSortSub(a,b);    }        private static int[] mergeSortSub(int[] a,int[] b){                int[] result=new int[a.length+b.length];        int i=0,j=0,k=0;                while(i<a.length && j<b.length)        {            if(a[i]<b[j])                result[k++]=a[i++];            else                result[k++]=b[j++];        }        while(i<a.length)            result[k++]=a[i++];        while(j<b.length)            result[k++]=b[j++];                return result;    }}

 

归并排序