合并算法详解原理和代码

阿里数据库,腾讯数据库之合并算法
对于算法初学者,合并算法可能是一个比较难的算法,那么到底合并算法的原理是什么呢?下面我就给大家介绍一下。
首先,合并算法,需要经过,分解,排序,合并三步骤。
就是将一串足够大的数据,分解成一个个小单元去进行单独排序,然后再将这些小单元依次两两相邻合并,再次排序,循环下去,直到全部合并,最后整个进行排序。
12,65,87,56,97,65,76,45,87,98
这是一组数据,先分解,从中间断开,分解为两组数据。
12,65,87,56,97
65,76,45,87,98
然后再次分解,成为六组数据
12,65 ------ 87,56-------- 97
65,76-------45,87--------- 98
再次分解当达到最小单元一个数据时停止分解,这时成为了十个数组。
依次排序
12—65----87—56----97----65----76----45—87—98
然后两两合并
12,65------87,56-----97,65-----76,45-----87,98
接着排序:12,65------56,87-----65,97-----45,76-----87,98
此次循环下去最后排出结果。12,45,56,65,65,87,87,97,98
当数据非常大时,这种排序能够大大减小时间复杂度。

package iii;

import java.util.Arrays;

public class addsort1 {

	public static void main(String[] args) {
		int[] a= {18,37,98,267,398,26,38,462,16};
		Sort(a,0,a.length-1);
	}
	public static void Merge(int[] array,int low,int mid,int high)
	{
		int[] temp=new int[high-low+1];
		int L=low;
		int R=mid+1;
		int i=0;
		while(L<=mid&&R<=high)
		{
			if(array[L]<array[R])
			{
				temp[i++]=array[L++];
			}
			else
			{
				temp[i++]=array[R++];
			}
		}
		while(L<=mid)
		{
			temp[i++]=array[L++];
		}
		while(R<=high)
		{
			temp[i++]=array[R++];
		}
		for(int n=0;n<temp.length;n++)
		{
			array[n+low]=temp[n];
		}
		System.out.println(Arrays.toString(array));
	}
    public static void Sort(int[] array,int low,int high)
    {
    	if(low==high)
    	{
    		return;
    	}
    	int mid=(high+low)/2;
    	if(low<high)
    	{
    		Sort(array,low,mid);   
    		Sort(array,mid+1,high);
    		Merge(array,low,mid,high);
    	}
    }
}

有不同方法或者观点的小伙伴可以在下方评论,共同学习,共同进步。当然有问题的也可以提出。

发布了3 篇原创文章 · 获赞 6 · 访问量 149

猜你喜欢

转载自blog.csdn.net/burning_passion/article/details/104794434