/* Quicker Sequential Search.
*
* Implementation history:
* 2013-10-4, Mars Fu, using @pointer to replace @index for improving addressing.
*/
/* Modifying from:
* [Quicker Sequential Search Algorithm]
* Published by D.E.Knuth, Computing Surveys 6 (1974).
*/
#include "stdafx.h"
#include "quicker_sequential_search.h"
int
do_quicker_sequential_search(void *key, void *src, int src_sz, int n, cmp_func cmp)
{
char *s;
char *e;
int u;
F_S();
if (key == NULL || src == NULL || cmp == NULL) return 0;
if (src_sz <= 0 || n <= 0) return 0;
s = (char*)src;
e = s + (n-1) * src_sz;
u = src_sz << 1;
for (; s < e; s += u) {
if (cmp(key, s) == 0) goto END;
if (cmp(key, s + src_sz) == 0) goto END;
}
if (s == e + src_sz) {
if (cmp(key, e) == 0) goto END;
}
return 0;
END:
F_E();
return 1;
}
#ifdef QUICKER_SEQUENTIAL_SEARCH_DEBUG
int
int_cmp(void* lv, void* rv)
{
int tmp_lv, tmp_rv;
tmp_lv = *(int*)lv;
tmp_rv = *(int*)rv;
return (tmp_lv - tmp_rv);
}
int
main(int argc, char* argv[])
{
int i;
int cnt;
int ret;
int int_items[16] = { 503, 87, 512, 61, 908, 170, 897, 275,
653, 426, 154, 509, 612, 677, 765, 703
};
int key;
debug("[Debug quicker sequential search].. \r\n");
cnt = sizeof(int_items)/sizeof(int_items[0]);
debug("src database:\r\n----\r\n");
for (i = 0; i < cnt; ++i) {
debug("%d ", int_items[i]);
}
debug("\r\n----\r\n");
key = int_items[0];
debug("search key %d... \r\n", key);
ret = do_quicker_sequential_search(&key, int_items, sizeof(int), cnt, int_cmp);
if (!ret) debug("not found.\r\n");
debug("\r\n----\r\n");
key = int_items[cnt-1];
debug("search key %d... \r\n", key);
ret = do_quicker_sequential_search(&key, int_items, sizeof(int), cnt, int_cmp);
if (!ret) debug("not found.\r\n");
debug("\r\n----\r\n");
key = int_items[cnt/2];
debug("search key %d... \r\n", key);
ret = do_quicker_sequential_search(&key, int_items, sizeof(int), cnt, int_cmp);
if (!ret) debug("not found.\r\n");
debug("\r\n----\r\n");
key = 12345;
debug("search key %d... \r\n", key);
ret = do_quicker_sequential_search(&key, int_items, sizeof(int), cnt, int_cmp);
if (!ret) debug("not found.\r\n");
debug("[Debug quicker sequential search]..done. \r\n");
while (1);
return 1;
}
#endif /* QUICKER_SEQUENTIAL_SEARCH_DEBUG */
#ifndef __QUICKER_SEQUENTIAL_SEARCH_H__
#define __QUICKER_SEQUENTIAL_SEARCH_H__
#define QUICKER_SEQUENTIAL_SEARCH_DEBUG
typedef int(*cmp_func)(void*,void*);
int do_quicker_sequential_search(void *key, void *src, int src_sz, int n, cmp_func cmp);
#endif /* __QUICKER_SEQUENTIAL_SEARCH_H__ */
#pragma once
#include <windows.h>
#ifdef _WIN32
#define msleep(x) Sleep(x)
#endif
#include <stdio.h>
#include <tchar.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <math.h>
#define MY_DEBUG
#ifdef MY_DEBUG
#define debug printf
#else
#define debug(x,argc, __VA_ARGS__) ;
#endif /* MY_DEBUG */
#define F_S() debug("[%s]..\r\n", __FUNCTION__)
#define F_E() debug("[%s]..done. \r\n", __FUNCTION__)
Enjoy~
Mars
October 4, 2013