归并排序详细解析

我们先来一个两个有序的数组a和b进行排序的代码,两个有序的数组进行排序只需每次选择两个数组中最小的那个数放进c中就ok了,之后如果那个数组还有剩余就将其直接接在c后面。时间效率还是很快的达到了O(n)。

python源码

def MemeryArray(a,b,c):
    i = 0
    j = 0
    k = 0
    n = len(a)
    m = len(b)
    while i<n and j<m:
        if a[i]<b[j]:
            c.append(a[i])
            k = k + 1
            i = i + 1
        else:
            c.append(b[j])
            k = k + 1
            j = j + 1
    while i<n:
        c.append(a[i])
        k = k + 1
        i = i + 1
    while j<m:
        c.append(b[j])
        k = k + 1
        j = j + 1
    print c


#测试memery函数数据
a = [1,3,5,7,12,19]
b = [2,5,6,8,9,10]
c = list()
MemeryArray(a,b,c)


C++源码

void MemeryArray(int a[], int n, int b[], int m, int c[])
{
	int i, j, k;

	i = j = k = 0;
	while (i < n && j < m)
	{
		if (a[i] < b[j])
			c[k++] = a[i++];
		else
			c[k++] = b[j++]; 
	}

	while (i < n)
		c[k++] = a[i++];

	while (j < m)
		c[k++] = b[j++];
}


如果将一个无序的数组怎么进行归并排序呢,我们可以这样想,单个元素相当于一个有序的序列,只需将其两两合并,只要循环log(n)次就可以了。我们通过递归将其递归到单个元素的情况,之后两两排序返回。时间复杂度为O(log(n)*n)。

python源码

def mergearray(a,first,mid,last):
    temp = []
    i = first
    j = mid + 1
    m = mid
    n = last
    k = 0

    while i<=m and j<=n:
        if a[i] <= a[j]:
            temp.append(a[i])
            k = k + 1
            i = i + 1
        else:
            temp.append(a[j])
            k = k + 1
            j = j + 1

    while i<=m:
        temp.append(a[i])
        k = k + 1
        i = i + 1

    while i<=m:
        temp.append(a[j])
        k = k + 1
        j = j + 1

    for i in range(0,k):
        a[first + i] = temp[i]


def mergesort(a,first,last):
    if first<last:
        mid = (first+last)/2
        mergesort(a,first,mid)
        mergesort(a,mid+1,last)
        mergearray(a,first,mid,last)

def MergeSort(a):
    mergesort(a,0,len(a)-1)
    print a


a = [5,1,3,6,19,10,12,4,7]
MergeSort(a)


C++源码

void mergearray(int a[], int first, int mid, int last, int temp[])
{
	int i = first, j = mid + 1;
	int m = mid,   n = last;
	int k = 0;
	
	while (i <= m && j <= n)
	{
		if (a[i] <= a[j])
			temp[k++] = a[i++];
		else
			temp[k++] = a[j++];
	}
	
	while (i <= m)
		temp[k++] = a[i++];
	
	while (j <= n)
		temp[k++] = a[j++];
	
	for (i = 0; i < k; i++)
		a[first + i] = temp[i];
}
void mergesort(int a[], int first, int last, int temp[])
{
	if (first < last)
	{
		int mid = (first + last) / 2;
		mergesort(a, first, mid, temp);   
		mergesort(a, mid + 1, last, temp); 
		mergearray(a, first, mid, last, temp); 
	}
}

bool MergeSort(int a[], int n)
{
	int *p = new int[n];
	if (p == NULL)
		return false;
	mergesort(a, 0, n - 1, p);
	delete[] p;
	return true;
}






郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。