归并算法

归并算法:实现排序。

归:递归。并:合并。

如何递归,如何合并?

使用归并算法的优点:算法的时间复杂度和空间复杂度低。

import java.util.Arrays;

/**
 * 归并排序程序,要求输入10个整数,输出排序结果
 * Created by ZL on 2016/8/19.
 */
public class Fourth {
    public static void main(String[] args) {
         int[] arr = {9,8,7,6,5,4,3,2,1,0};
         sort(arr,0,arr.length-1);
    }

    public static void sort(int[] arr,int left,int right){
        if(left>=right)
            return;
        int center = (left+right)>>1;
        sort(arr,left,center);
        sort(arr,center+1,right);
        merge(arr,left,center,right);

    }

    public static void merge(int[] arr,int left,int center,int right){
        int[] tempArr = new int[right+1];
        int mid = center+1;
        int index = left;
        int temp = left;

        //从两个数组找到最小放入临时数组tempArr
        while(left<=center&&mid<=right){
            tempArr[index++] = (arr[left]<=arr[mid])?arr[left++]:arr[mid++];
            //System.out.println(Arrays.toString(tempArr));
        }
        //剩余加入临时数组
        while(mid<=right){
            tempArr[index++] = arr[mid++];
        }
        while(left<=center){
            tempArr[index++] = arr[left++];
        }
        // 将临时数组中的内容复制到原数组
        for(int i=temp;i<=right;i++){
            arr[i] = tempArr[i];
        }
       // System.out.println(Arrays.toString(arr));
    }
}

 

posted on 2016-08-19 11:40  青木堂  阅读(311)  评论(0)    收藏  举报

导航