转载出处:http://blog.csdn.net/qzfzz/article/details/9564025
//BlockSearch.h
#ifndef BLOCK_SEARCH
#define BLOCK_SEARCH
#include <stdio.h>
#include <stdlib.h>
#define ARR_SIZE 100
#pragma pack(push)
#pragma pack(4)
typedef struct
{
int iStart;
int iEnd;
int iMax;
}INode;
typedef struct
{
int* pArr;
int iSize;
INode* pNode;
int iNodeSize;
}BlockSeq;
#pragma pack(pop)
#endif
//BlockSearch.c
#include "BlockSearch.h"
int BlockSearch( BlockSeq* pBSeq, int iTarget )
{
if( !pBSeq || 0 == iTarget )
return -1;
int i = 0;
for( ; i < pBSeq->iNodeSize; i++ )
{
if( (pBSeq->pNode + i)->iMax > iTarget )
break;
}
if( i >= pBSeq->iNodeSize )
return -1;
int j;
int iMaxIndex = ( pBSeq->pNode + i )->iEnd;
for( j = ( pBSeq->pNode + i )->iStart; j <= iMaxIndex; j++ )
{
if( *(pBSeq->pArr + j) == iTarget )
return j;
}
return -2;
}
BlockSeq* CreateBlockSeq()
{
BlockSeq *pBSeq = (BlockSeq*)malloc( sizeof( BlockSeq ) );
if( !pBSeq )
return NULL;
pBSeq->pArr = (int*)malloc( sizeof( int ) * ARR_SIZE );
pBSeq->iSize = ARR_SIZE;
pBSeq->pNode = (INode*)malloc( sizeof( INode ) * 4 );
pBSeq->iNodeSize = 4;
int i = 1;
for( ; i <= 100; i++ )
{
*( pBSeq->pArr + i - 1 ) = i;
}
pBSeq->pNode->iStart = 0;
pBSeq->pNode->iMax = 25;
pBSeq->pNode->iEnd = 24;
( pBSeq->pNode + 1 )->iStart = 25;
( pBSeq->pNode + 1 )->iMax = 50;
( pBSeq->pNode + 1 )->iEnd = 49;
( pBSeq->pNode + 2 )->iStart = 50;
( pBSeq->pNode + 2 )->iMax = 75;
( pBSeq->pNode + 2 )->iEnd = 74;
( pBSeq->pNode + 3 )->iStart = 75;
( pBSeq->pNode + 3 )->iMax = 100;
( pBSeq->pNode + 3 )->iEnd = 99;
return pBSeq;
}
int main( int argc, char* argv[] )
{
BlockSeq *pBSeq = CreateBlockSeq();
printf( "Result is: %d", BlockSearch( pBSeq, 33 ) );
puts( "" );
return 0;
}