1. Principle
Our common merge sort, also known as 2路归并排序
, is equivalent to the operation of combining two sequential lists or linked lists. If we achieve this through the dichotomy, dividing a long sequence table into the smallest subsequence all the way to the smallest subsequence, and then gradually merging from the smallest subsequence into a large table, then the final large table will be ordered.
So this is a recursive process with a time complexity of nlog 2 n nlog_2nn l o g2n
Two. Process
Because it is a recursive process, it is more convenient to show together
Suppose that the elements of an ordered list are n+1 elements from 0 to n, where the start represents l, the end represents h, and the middle element is represented by m=(l+h)/2. The
recursive expression can be written as:
sort (l , h) = {l = h, recursive termination l <h, sort (l, m); sort (m + 1, h); and merge sort(l,h) = \begin(cases) l = h,& Recursive termination \\ l <h, &sort(l,m); sort(m+1,h); and merge \\ \end(cases)s o r t ( l ,h)={
l=h,l<h,Hands go the final stops o r t ( l ,m);sort(m+1,h);And closing and
Three. Code
#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 100
int temp[MAXLEN] = {
0}; //创建一个临时变量数组
int Mergelist(int arry[], int low, int mid,int high)
{
int tptr, lptr, hptr, i = 0;
tptr = 0; // 临时数组储存下标
lptr = low; // 左序列下标,low<=lptr<=mid
hptr = mid + 1; // 右序列下标,mid+1<=hptr<=high
while(lptr <= mid && hptr <= high) // 这三个while就是循环合并两个线性表
{
// 将左序列或右序列中,较小的存入临时数组里
if (arry[lptr] <= arry[hptr])
{
temp[tptr] = arry[lptr];
++lptr;
}
else
{
temp[tptr] = arry[hptr];
++hptr;
}
++tptr;
}
// 检测左序列是否添加完毕
while(lptr <= mid)
{
temp[tptr] = arry[lptr];
++lptr;
++tptr;
}
// 检测右序列是否添加完毕
while(hptr <= high)
{
temp[tptr] = arry[hptr];
++hptr;
++tptr;
}
// 将新序列覆盖原数组
for (; i < tptr; ++i)
{
arry[low+i]=temp[i];
}
}
int MergeSort(int arry[], int low, int high)
{
int mid;
if (low < high) // 可递归部分
{
mid = (low + high) / 2;
MergeSort(arry, low, mid); // 左序列
MergeSort(arry, mid+1, high); // 右序列
Mergelist(arry, low, mid, high); // 合并两序列
}
}
int main()
{
int a[7] = {
6,5,3,7,2,1,4};
int i;
MergeSort(a, 0, 6);
for (i = 0; i < 7; ++i)
{
printf("%d ", a[i]);
}
return 0;
}