归并排序是分治法(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++];
}
}