码迷,mamicode.com
首页 > 编程语言 > 详细

算法学习总结(四):归并排序

时间:2016-07-22 16:09:20      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

一、算法分析

     原理:将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并。

     归并排序的时间复杂度为o(n*log2n)

二、代码示例

public class MergeSort {
    public int[] mergeSort(int[] A, int n) {
        // write code here
       sort(A,0,n-1);
       return A;
    }
     
        public void sort(int[] data,int left,int right){
            if(left<right){
                int middle=(left+right)/2;
                //划分左右
                sort(data,left,middle);
                   sort(data,middle+1,right);
                //合并左右
                merge(data,left,middle,right);
            }
        }
        
        //合并左右两个子数组
        public void merge(int[] data,int left,int middle,int right){
            //临时数组
            int[] tempArr=new int[right-left+1];
            //左边数组游标
            int leftIndex=left;
            //右边数据游标
            int rightIndex=middle+1;
            //临时数组游标
            int tempIndex=0;
            
            while(leftIndex<=middle&&rightIndex<=right){
                //临时数组选取左、右子数组中小数值
               if(data[leftIndex]<data[rightIndex]){
                   tempArr[tempIndex++]=data[leftIndex++];
               }else{
                   tempArr[tempIndex++]=data[rightIndex++];
               }
            }
            //剩余的直接放入
            while(leftIndex<=middle){
                   tempArr[tempIndex++]=data[leftIndex++];
            }
            //剩余的直接放入
            while(rightIndex<=right){
                   tempArr[tempIndex++]=data[rightIndex++];
            }
            //将临时数组放回原数组相应位置
            int temp=0;
            while((temp+left)<=right){
                data[left+temp]=tempArr[temp];
                temp++;
            }
        }
}

 

算法学习总结(四):归并排序

标签:

原文地址:http://www.cnblogs.com/gugibv/p/5695515.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!