MergeSort 归并排序,可以理解为将把需要排序的内容分成两部分,排序完之后再合并起来。
void merge(int a[],int b[],int low,int mid,int high)
{
int s = low , t = mid + 1, k = low;
while(s<=mid&&t<=high)
{
if(a[s] < a[t]){
b[k] = a[s];
s++;
}
else{
b[k] = a[t];
t++;
}
K++;
}
if(s == mid + 1)
{
for(i=k;i<=high;i++)
b[i] = a[t++];
}
else
{
for(i=k;i<=high;i++)
b[i] = a[s++];
}
}
void MergeSort(int a[],int b[],int low,int high)
{
if(low<high)
{
int mid = (low + high)/2;
MergeSort(a,b,low,mid);
MergeSort(a,b,mid+1,high);
Merge(a,b,low,mid,high);
}
}
MergeSort python实现
def Merge(left,right):
result = []
i,j = 0,0
while(i < len(left) and j < len(right)):
if(left[i] < right[j]):
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while(i < len(left)):
result.append(left[i])
i += 1
while(j < len(right)):
result.append(right[j])
j += 1
return result
def MergeSort(L):
if(len(L) < 2):
return L[:]
else:
mid = int(len(L)/2)
left = MergeSort(L[:mid])
right = MergeSort(L[mid:])
return Merge(left,right)