Java算法学习-----------------归并排序算法

时间:2022-02-07 12:44:04

将数组中的相邻元素两两配对,用归并算法进行排序,构成n/2组长度为2的排好序的子数组段,然后再将其排成长度为4的子数组段,如此继续下去直到整个数组排好序。

按照此思想,消除递归后的归并排序算法(伪代码)如下:

public class MergeSort {
	
	public static void mergeSort(Comparable[]a)
	{
		Comparable[]b=new Comparable[a.length];
		int s=1;
		while (s<a.length)
		{
			mergePass(a,b,s);//合并到数组b
			s+=s;
			mergePass(b,a,s);//合并到数组a
			s+=s;
		}
	}

	private static void mergePass(Comparable[] x, Comparable[] y, int s) 
	{//合并大小为s的相邻数组
		int i=0;
		while (i<=x.length-2*s) 
		{//合并大小为s的两端相邻字数组
			merge(x,y,i,i+s-1,i+s*2-1);
			i=i+2*s;
		}
		//剩下的元素个数小于2s
		if (i+s<x.length) 
		{
			merge(x, y, i, i+s-1, x.length-1);
		}
		else//复制到y 
		{
			for (int j = i; j < x.length; j++) 
			{
				y[j] = x[j];
			}
		}
	}

	private static void merge(Comparable[] c, Comparable[] d, int l, int m, int r) 
	{
		//合并c[l:m]和c[m+1,r]到d[l:r]
		int i=1, j=m+1,k=l;
		while (i<=m && j<=r) 
		{
			if (c[i].compareTo(c[j])<=0)
			{
				d[k++]=c[i++];
			}
			else
			{
				d[k++]=c[j++];
			}
		}
		
		if (i>m)
		{
			for (int k2 = 0; k2 <=r; k2++) 
			{
				d[k++] = c[k2];
			}
		}
		else
		{
			for (int k2 = 0; k2 <=m; k2++) 
			{
				d[k++] = c[k2];
			}
		}
	}
}