数据结构算法之排序系列Java、C源码实现(7)--归并排序

 归并排序是将两个或两个以上的有序子表合并成一个新的有序表。初始时,把含有n个结点的待排序序列看做是由n个长度为1的有序表所组成,然后两两归并,得到个长度为2或1的有序子序列;再两两合并,…,如此重复,直至得到一个长度为n的有序序列为止。时间复杂度为O(nlog2n),所需辅助空间为O(n)。 一般情况下,对m个元素进行k路归并时,归并的趟数为:


该代码的思想就是最后分治为两个数据的合并(然后扩大成合并两个有序的数组)

java代码:

package 排序系列;

public class MergeSort {
public static void main(String[] args) {
int array[] = {5, 18, 151, 138, 160, 63, 174, 169, 79, 200};
showArray(array);
System.out.println("\n排序后");
mergeSort(array,0,array.length-1);
showArray(array);
}
private static void mergeSort(int[] a,int left,int right) {
int i;
//保证最低至少有两个元素 
if(left < right) {
i = (left + right)/2;
mergeSort(a,left,i);
mergeSort(a,i+1,right);
merge(a,left,right);
}
}
private static void merge(int[] a, int left, int right) {
int begin1 = left;
int mid = (left+right)/2;
int begin2 = mid + 1;
int newArrayLen = right-left +1;
int k = 0;
int[] b = new int[newArrayLen];
while(begin1<=mid && begin2<=right)
{
if(a[begin1]<= a[begin2])
b[k++] = a[begin1++];
else
b[k++] = a[begin2++];
}
while(begin1<= mid)
{
b[k++] = a[begin1++];
}
while(begin2<=right)
{
b[k++] = a[begin2++];
}
copyArray(b,a,newArrayLen,left);
}
private static void copyArray(int source[],int dest[],int len,int first)
{
int j = first;
int i;
for(i=0;i<len;i++){
dest[j] = source[i];
j++;
}
}
private static void showArray(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}


你可能感兴趣的:(java,数据结构,源码,归并排序,C语言)