题目:随机生成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("排序失败. "); } else { printf("排序后: "); for (i = 0; i < 10; i++) { printf("%d ", data[i]); } printf(" "); } int nFind = 0; if (BinSort(data, 0, 9, 9, &nFind) == 0) { printf("查找失败. "); } else { if (nFind == 1) { printf("查找成功. "); } else { printf("查找不成功. "); } } if (BinSortPtr(data, 0, 9, 9, &nFind) == 0) { printf("查找失败. "); } else { if (nFind == 1) { printf("查找成功. "); } else { printf("查找不成功. "); } } system("pause"); return 0; }运行效果如图1所示:
图1 运行效果