linear hash

// linear_hash.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdio.h>
#include <assert.h>

#define UNUSED (-1)


/*
* Linear Hash is to search a position where is no element used
* from the position which hash function specified.
* Param:
* arr: A array to save new element.
* len: Length of that array.
* x: The new element to put.
* Rtn:
* 0: Insert successfully.
* -1: No space.
* Note:
* For more details, please see <<Operating Systems Internals
* and Design Principles Sixth Edition>> Chinese version page .269
*/
static int linear_hash(int arr[], int len, int x)
{
assert(NULL != arr) ;
assert(0 < len) ;

int cnt = 0 ; // Count how many elements has been passed.
int pos = x % len ;
while (UNUSED != arr[pos])
{
pos = (pos + 1) % len ;

// When there is no space to restore any
// new element, function return -1.
if (++cnt == len - 1)
{
return -1 ;
}
}

arr[pos] = x ;

return 0 ;
}


int _tmain(int argc, _TCHAR* argv[])
{
int arr[] = {UNUSED, 1, 5, UNUSED, UNUSED, 3, UNUSED, 4, UNUSED, 8, UNUSED} ;
int len = int(sizeof(arr)/sizeof(arr[0])) ;

for (int i = 0 ; i < (int)sizeof(arr)/sizeof(arr[0]) ;i++)
{
printf("%4d ", arr[i]) ;
}
puts("") ;

// '0' should put at arr[0], and arr[0] is unused,
// thus arr[0] = 0.
linear_hash(arr, len, 0) ;
// '2' should put at arr[2], but arr[2] == 5,
// and then, we look at arr[(2+1) % len], which is UNUSED,
// thus arr[(2+1) % len] = 2.
linear_hash(arr, len, 2) ;

for (int i = 0 ; i < len ;i++)
{
printf("%4d ", arr[i]) ;
}
puts("") ;

return 0;
}

posted @ 2011-11-28 19:54  walfud  阅读(482)  评论(0编辑  收藏  举报