1、时间复杂度:
最优情况:o(n);
最坏情况:o(nlogn)
将待排序的序列分成若干子序列,并且每个子序列是有序的,再将每个子序列两两进行排序,合并,最终整体有序。
2、算法步骤:
(1)先将序列拆分成两个子序列;
(2)将两个子序列之间进行排序,合成一个;
(3)重复(1)(2)过程,进行递归,直至每个序列个数为1时,终止递归。
3、改进思想
(1)对于小数组(长度小于一定值时),采取插入排序,处理速度上会有所提升。
4、归并排序实现代码
/***************************************************************************
* @file main.c
* @author HAOJIEFENGLANG
* @date 5 August 2018
* @remark 5 August 2017
* @theme Merge sort
*************************************************************
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 10
void Merging(int *list1, int list1_size, int * list2, int list2_size);
//1、先拆再合
void MergeSort(int a[], int n)
{
if (n > 1)
{
//拆分为两半,list1是前一半,list2是后一半
int *list1 = a;
int list1_size = n / 2;
int *list2 = a + n / 2;
int list2_size = n - list1_size;
//递归对两个子序列进行分割
MergeSort(list1, list1_size);
MergeSort(list2, list2_size);
Merging(list1, list1_size, list2, list2_size);
}
}
//实现归并,并把结果放在list1中,并且因为list指向的是a[],所以a[]也发生了改变;
void Merging(int *list1, int list1_size, int * list2, int list2_size)
{
int i, j, k, m;
int temp[MAXSIZE] = { 0 };
i = j = k = m = 0;
while (i < list1_size&&j < list2_size)
{
if (list1[i] < list2[j])
{
temp[k++] = list1[i++];
}
else
{
temp[k++] = list2[j++];
}
}
//导致上述条件终止的情况有两种,所以还有把每个子序列余下的元素放入到temp中
while (i < list1_size)
{
temp[k++] = list1[i++];
}
while (j < list2_size)
{
temp[k++] = list2[j++];
}
for (m = 0; m < (list1_size + list2_size); m++)
{
list1[m] = temp[m];
}
}
int main()
{
int a[10] = { 1,0,2,3,4,5,6,7,8,9 };
int n = 10;
MergeSort(a, n);
printf("归并排序后为: ");
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}