MergeSort(归并排序)算法的java实现

归并排序是分治法(divide and conquer)的一个典型应用。
归并排序(MergeSort)实际上是首先将n个数据视为长度为l的n个表,并合并相邻表对以获得长度为2的n / 2个排序列表; 成对的相邻表格被合并以获得长度为4的n / 4个有序列表;...; 直到所有数据合并为长度为n的有序列表,这意味着排序完成。
上述每个合并过程都称为Pass。 整个排序过程都是双向合并排序。

双向合并排序算法MergeSort将一个序列分解成两个长度几乎相等的子序列,分别对它们进行排序,然后调用Merge函数将两个有序子序列合并为一个有序序列以完成合并排序。 代码实现如下:

public class MergeSort {
	static int[] test;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] test= {35,40,62,49,45,89,23};
		DivideAndMerge(test,0,test.length-1);
		for(int i=0;i<test.length;i++) {
			System.out.print(test[i]+" ");
		}
	}
	static void DivideAndMerge (int[] array,int left,int right) {
		if (left<right) {	// When the sequence length is greater than 1, further division
			int mid=(left+right)/2;	// split into two
			//System.out.print(left);System.out.print(mid);System.out.print(right);	
			DivideAndMerge (array,left,mid);	// Sorting the left subsequence elements
			DivideAndMerge (array,mid+1,right);	// Sorting the right subsequence elements
			Merge(array,left,mid,right);	// Merging into an ordered sequence
		}
	}
	static void Merge (int [] a,int left,int mid,int right) {  // Two-way merge sort algorithm (Merge function)
		  int[] temp=new int[right-left+1];  // Allocate space for array temp
	      int k=0; 		      // k is the current position in array temp
	      int i=left,	j=mid+1;  // i is the current position of the left subsequence; j is the current position of the right subsequence
	      while ((i<=mid) && (j<=right))
		      if (a[i]<=a[j])	temp[k++]=a[i++];
		      else 	temp[k++]=a[j++];
	      while (i<=mid)   temp[k++]=a[i++];
	      while (j<=right)  temp[k++]=a[j++];
	      for (i=0,k=left;k<=right;)   // Write back array I from array temp
	    	  	  a[k++]=temp[i++];  
	      
	}
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值