归并排序——含代码

来源:互联网 发布:可爱的便签软件 编辑:程序博客网 时间:2024/06/09 22:55

对于无序数组进行排序,效率优于冒泡、选择、插入排序

直接上代码:

public class Test {    public static void main(String[] args) {        int[] a  = new int[]{3,5,2,7,9,2,5,22,4,1};        mergeSort(a, new int[10], 0, 9);        for (int i : a) {            System.out.println(i);        }    }    private  static void mergeSort(int[] ori,int[] tmp,int underBound,int upperBound) {        // TODO Auto-generated method stub        if(underBound==upperBound){            return;        }else{            int mid = (underBound+upperBound)/2;            mergeSort(ori, tmp, underBound, mid);            mergeSort(ori, tmp, mid+1, upperBound);            merge(ori, tmp, underBound, upperBound);        }    }    private static void merge(int[] ori,int[] tmp,int underBound,int upperBound) {        int under = underBound;        int mid = (underBound+upperBound)/2;        int up = mid+1;        int tmpCount = 0;        while(under<=mid&&up<=upperBound){            if(ori[under]>ori[up]){                tmp[tmpCount++] = ori[up++];            }else{                tmp[tmpCount++] = ori[under++];            }        }        while(under<=mid){            tmp[tmpCount++] = ori[under++];        }        while(up<=upperBound){            tmp[tmpCount++] = ori[up++];                    }        for (int i = 0; i < tmpCount; i++) {            ori[underBound++] = tmp[i];        }    }}

0 0
原创粉丝点击