创建索引顺序表和分块查找

转载出处: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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值