题目:随机生成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 运行效果