【算法】归并排序 merge sort

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int a[15] = {15,14,13,12,11,10, 9, 8, 7, 6, 5, 4, 3, 2, 1};

void merge_sort (int l_num, int h_num)
{
	int k = l_num;
	int m = (h_num+l_num)/2+1;
	int i = 0;
	int *b = NULL;
	int j = 0;
	
        printf("low index is %d, high index is %d.\n", l_num, h_num);
	if (l_num == h_num)
	{
		printf("We have got to the leaf.\n");
		return;
	}

	merge_sort(l_num,(h_num+l_num)/2);
	merge_sort((h_num+l_num)/2+1, h_num);
	
	b = malloc((h_num-l_num+1)*sizeof(int));
        if (NULL == b)
        {
                printf("Failed to alloc memory.\n");
		return;
        }
	
	printf ("Low index is %d, high index is %d.\n", l_num, h_num);

	for (j = 0; j <= h_num-l_num; j++)
	{
		if ((m > h_num)||(a[k] < a[m]))
		{
			b[j]=a[k++];
		}
		else
		{	b[j]=a[m++];
		}
	}
	
	for (j = l_num; j <= h_num; j++)
	{
		a[j] = b[i++];
		printf("Index: %d, Num: %d.\n", j, a[j]);
	}
	
	free(b);
}

void main()
{	
	int i = 0;
	merge_sort(0, 14);

	for (i=0; i<14; i++)
	{	
		printf ("Final result index: %d, %d.\n", i, a[i]);
	}
	return;
}


归并排序的算法复杂度为  n*lgn

插入排序的复杂度为 n*n,

当n增长到 30后,  归并算法速度快

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值