随机生成1024个数,用指针进行排序,并实现二分查找

题目:随机生成1024个数,用指针进行排序,并实现二分查找,具体实现如下:

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

int SortByPtr(int * pInput, int nLen)
{
	if (!pInput)
	{
		return 0;
	}
	int * pCur = pInput;
	int * pEnd = pInput + nLen;
	int * pCur2 = NULL;
	int * pEnd2 = pEnd;
	int nTemp = 0;
	for (; pCur < pEnd - 1; pCur++)
	{
		for (pCur2 = pEnd2-1; pCur2 > pCur; pCur2--)
		{
			if (*pCur2 < *(pCur2 - 1))
			{
				nTemp = *pCur2;
				*pCur2 = *(pCur2 - 1);
				*(pCur2 - 1) = nTemp;
			}
		}
	}
	return 1;
}

int BinSort(int * pInput, int nLow, int nHigh, int nKey, int * pFind)
{
	if (!pInput || !pFind)
	{
		return 0;
	}

	*pFind = 0;

	if (nLow > nHigh)
	{
		return 1;
	}

	int nMid = (nHigh + nLow) / 2;

	if (pInput[nMid] == nKey)
	{
		*pFind = 1;
		return 1;
	}
	else if (pInput[nMid] > nKey)
	{
		return BinSort(pInput, nLow, nMid - 1, nKey, pFind);
	}
	else
	{
		return BinSort(pInput, nMid + 1, nHigh, nKey, pFind);
	}
}

int BinSortPtr(int * pInput, int nLow, int nHigh, int nKey, int * pFind)
{
	if (!pInput || !pFind)
	{
		return 0;
	}

	*pFind = 0;

	if (nLow > nHigh)
	{
		return 1;
	}

	int nMid = (nHigh + nLow) / 2;

	int * pTemp = pInput + nMid;

	if (*pTemp == nKey)
	{
		*pFind = 1;
		return 1;
	}
	else if (*pTemp > nKey)
	{
		return BinSort(pInput, nLow, nMid - 1, nKey, pFind);
	}
	else
	{
		return BinSort(pInput, nMid + 1, nHigh, nKey, pFind);
	}
}
int main()
{
	int data[10] = { 4, 5, 1, 3, 2, 0, 6, 7, 9, 8 };
	int i = 0;
	if (SortByPtr(data, 10) == 0)
	{
		printf("排序失败.\n");
	}
	else
	{
		printf("排序后:\n");
		for (i = 0; i < 10; i++)
		{
			printf("%d	", data[i]);
		}
		printf("\n");
	}
	int nFind = 0;
	if (BinSort(data, 0, 9, 9, &nFind) == 0)
	{
		printf("查找失败.\n");
	}
	else
	{
		if (nFind == 1)
		{
			printf("查找成功.\n");
		}
		else
		{
			printf("查找不成功.\n");
		}
	}
	if (BinSortPtr(data, 0, 9, 9, &nFind) == 0)
	{
		printf("查找失败.\n");
	}
	else
	{
		if (nFind == 1)
		{
			printf("查找成功.\n");
		}
		else
		{
			printf("查找不成功.\n");
		}
	}
	system("pause");
	return 0;
}
运行效果如图1所示:

图1 运行效果

转载于:https://www.cnblogs.com/new0801/p/6176905.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值