判断序列中是否存在两个元素之和为x,时间复杂度O(nlgn),算法导论练习2.3,linux纯C实现

代码可在anycodes在线编译测试


#include <stdio.h>
#include <stdbool.h>
bool binarySearch(int* a, int L, int N)
{
	int fI = 0, lI = L-1, mI = 0;
	while(fI <= lI)
	{
		mI = (fI+lI) >> 1;
		if(N > *(a+mI))
			fI = mI + 1;
		else if(N < *(a+mI))
			lI = mI - 1;
		else
			return true;	
	}
	return false;
}
bool search(int* a, int L, int N)
{
	int i = 0;
	for (;i<L-1;i++)
	{
		if(binarySearch(a, L, N-(*(a+i))))
			return true;
	}
	return false;
}
int binarySort(int* a, int fI, int lI, int N)
{
	int mI = (fI+lI) >> 1;
	if (N > *(a+mI))
	{
		fI = mI + 1;
		if(fI > lI)
			return mI+1;
		binarySort(a, fI, lI, N);
	}
	else if (N < *(a+mI))
	{
		lI = mI - 1;
		if(fI > lI)
			return mI;
		binarySort(a, fI, lI, N);
	}
	else
		return mI+1;
}
void insertSort(int* a, int index, int N)
{
	int key = *(a+index);
	if(index+1 <= N)
	{
		int i = binarySort(a, 0, index-1, key);
		int j = index-1;
		for (;j>=i;j--)
		{
			*(a+j+1) = *(a+j);
		}
		*(a+i) = key;
		insertSort(a, index+1, N);
	}
	return;
}
int main()
{
	int a[10] = {212,343,534,2,3,67,34,78,90,32};
	int L = sizeof(a)/sizeof(int);
	int i = 0;
	int x = 5360;
	insertSort(a, 1, L);
	for (;i<L;i++)
		printf("%d ",*(a+i));
	printf("\n");
	if(search(a, L, x))
		printf("Yes! \n");
	else 
		printf("No! \n");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值