根号n段归并排序(递归)

根号n段归并排序(递归)

题目描述

根号n 段合并排序算法:
将数组 划分为 根号n个子数组,每个子数组有根号n 个元素。然后递归地对分割后的子数组进行排序,最后将所得到的根号n 个排好序的子数组合并排序。

#include<stdio.h>
#include<math.h>
#include<iostream>
#include<algorithm>
using namespace std;
void Merging(int *arr, int first1, int last1, int first2, int last2)//将两个子数组合并排序
{
	int arr3[last2-first1+1];
	int arr1[last1-first1+1];
	int arr2[last2-first2+1];
	int c=last2-first1+1;
	int a=last1-first1+1;
	int b=last2-first2+1;
	int a1=0, b1=0, c1=0;
	for(int i=0;i<a;i++)
	{
		arr1[i]=arr[i+first1];
	}
	for(int i=0;i<b;i++)
	{
		arr2[i]=arr[i+first2];
	}
	for(a1=0, b1=0;a1<a&&b1<b; )
	{
		if(arr1[a1]<=arr2[b1])
		{
			arr3[c1]=arr1[a1];
			a1++;
			c1++;
		}
		else
		{
			arr3[c1]=arr2[b1];
			c1++;
			b1++;
		}
	}
	if(a1<a)
	{
		while(a1<a)
		{
			arr3[c1++]=arr1[a1++];
		}
	}
	else
	{
		while(b1<b)
		{
			arr3[c1++]=arr2[b1++];
		}
	}
	for(int i=0;i<c;i++)
	{
		arr[i+first1]=arr3[i];
	}
}
void mysort(int *arr, int first, int last)
{
	int size=last-first+1;
	int N=(int)sqrt(size);
	int i;
	if(size>3)
	{
		int first1, last1;
		for(i=0;i<N;i++)//分为根号n段
		{
			first1=first+N*i;
			last1=first1+N-1;
			mysort(arr, first1, last1);
		}
		mysort(arr, last1+1, last);//如果数组长度不是一个刚好的平方数,对剩余数组元素的处理
	}
	else
	{
		sort(arr+first, arr+last+1);
	}
	int first1, last1, first2, last2;
	first1=first;
	last1=first+N-1;
	first2=first;
	if(size>3)
	{
		for(i=1;i<N;i++)
		{
			first2=first+i*N;
			last2=first2+N-1;
			Merging(arr,first1, last1,first2, last2);
			last1+=N;
		}
		Merging(arr, first1, last2, last2+1, last);如果数组长度不是一个刚好的平方数,对剩余数组元素的处理
	}
}
int main()
{
	int N;
	scanf("%d", &N);
	int a[N];
	for(int i=0;i<N;i++)
	{
		scanf("%d", &a[i]);
	}
	mysort(a, 0, N-1);
	for(int i=0;i<N;i++)
	{
		printf("%d\n", a[i]);
	}
	while(1)
	{
	} 
}
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值