/* Binary search.
*
* Implementation history:
* 2013-10-5, Mars Fu, first version.
*/ /* [Binary Search Algorithm]
* Published by John Mauchly(1946) and D.H.Lehmer(1960).
*
* [Uniform Binary Search Algorithm]
* Published by D.E.Knuth(1963) and A.K.Chandra(1971).
*/ #include "stdafx.h"
#include "binary_search.h"
#include "quicksort.h" int
do_binary_search(void *key, void *src, int src_sz, int n, cmp_func cmp)
{
int li,ri,i;
char *p; F_S(); if (key == NULL || src == NULL || cmp == NULL) return 0;
if (src_sz <= 0 || n <= 0) return 0; li = 1;
ri = n;
while (li <= ri) { i = ((li + ri) >> 1); p = (char*)src + (i-1) * src_sz;
if (cmp(key, p) < 0) {
ri = i - 1;
}
else if (cmp(key, p) > 0) {
li = i + 1;
}
else {
goto END;
}
} return 0; END:
F_E();
return i;
} int
do_uniform_binary_search(void *key, void *src, int src_sz, int n, cmp_func cmp)
{
int i,m;
char *p; F_S(); if (key == NULL || src == NULL || cmp == NULL) return 0;
if (src_sz <= 0 || n <= 0) return 0; i = (n + 1) / 2;
m = n / 2;
while (1) { p = (char*)src + (i-1) * src_sz;
if (cmp(key, p) < 0) {
if (m == 0) return 0;
i -= ((m + 1) / 2);
}
else if (cmp(key, p) > 0) {
if (m == 0) return 0;
i += ((m + 1) / 2);
}
else {
goto END;
} m = m / 2;
} return 0;
END:
F_E();
return i;
} int
do_uniform_binary_search_2(void *key, void *src, int src_sz, int n, cmp_func cmp)
{
int i,j,k,h,m;
char *p;
int n2; F_S(); if (key == NULL || src == NULL || cmp == NULL) return 0;
if (src_sz <= 0 || n <= 0) return 0; /* formula:
* h(j) = (n + 2^(j-1)) / (2^j), where 1 <= j <= (int)lg(n) + 2.
*/
n2 = 2;
m = (int)(log((double)n) / log((double)n2)) + 2; for (i = (n + 1) / 2, j = 1, k = 2; j < m; ++j, k <<= 1) { h = (n + k) / (k << 1); p = (char*)src + (i-1) * src_sz;
if (cmp(key, p) < 0) {
if (h == 0) return 0;
i -= h;
}
else if (cmp(key, p) > 0) {
if (h == 0) return 0;
i += h;
}
else {
goto END;
}
} return 0;
END:
F_E();
return i;
} #ifdef BINARY_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);
} static void
exchange_int_item(void* lv, void* rv)
{
int tmp_lv, tmp_rv; tmp_lv = *(int*)lv;
tmp_rv = *(int*)rv; *(int*)lv = *(int*)rv;
*(int*)rv = tmp_lv;
} 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 binary 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"); ret = do_quick_sort((void*)int_items, sizeof(int), cnt,
int_cmp, exchange_int_item, NULL);
if (!ret) {
debug("failed. \r\n");
goto END;
} debug("src database sorted:\r\n----\r\n");
for (i = 0; i < cnt; ++i) {
debug("%d ", int_items[i]);
}
debug("\r\n"); debug("\r\n----\r\n");
key = int_items[0];
debug("search key %d... \r\n", key);
ret = do_binary_search(&key, int_items, sizeof(int), cnt, int_cmp);
if (!ret) debug("not found.\r\n");
ret = do_uniform_binary_search(&key, int_items, sizeof(int), cnt, int_cmp);
if (!ret) debug("not found.\r\n");
ret = do_uniform_binary_search_2(&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_binary_search(&key, int_items, sizeof(int), cnt, int_cmp);
if (!ret) debug("not found.\r\n");
ret = do_uniform_binary_search(&key, int_items, sizeof(int), cnt, int_cmp);
if (!ret) debug("not found.\r\n");
ret = do_uniform_binary_search_2(&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_binary_search(&key, int_items, sizeof(int), cnt, int_cmp);
if (!ret) debug("not found.\r\n");
ret = do_uniform_binary_search(&key, int_items, sizeof(int), cnt, int_cmp);
if (!ret) debug("not found.\r\n");
ret = do_uniform_binary_search_2(&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_binary_search(&key, int_items, sizeof(int), cnt, int_cmp);
if (!ret) debug("not found.\r\n");
ret = do_uniform_binary_search(&key, int_items, sizeof(int), cnt, int_cmp);
if (!ret) debug("not found.\r\n");
ret = do_uniform_binary_search_2(&key, int_items, sizeof(int), cnt, int_cmp);
if (!ret) debug("not found.\r\n"); debug("\r\n"); debug("[Debug binary search]..done. \r\n"); END:
while (1);
return 1;
} #endif /* BINARY_SEARCH_DEBUG */
#ifndef __BINARY_SEARCH_H__
#define __BINARY_SEARCH_H__ #define BINARY_SEARCH_DEBUG typedef int(*cmp_func)(void*,void*); int do_binary_search(void *key, void *src, int src_sz, int n, cmp_func cmp);
int do_uniform_binary_search(void *key, void *src, int src_sz, int n, cmp_func cmp);
int do_uniform_binary_search_2(void *key, void *src, int src_sz, int n, cmp_func cmp); #endif /* __BINARY_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 5, 2013

Foundation: Binary Search的更多相关文章

  1. [数据结构]——二叉树(Binary Tree)、二叉搜索树(Binary Search Tree)及其衍生算法

    二叉树(Binary Tree)是最简单的树形数据结构,然而却十分精妙.其衍生出各种算法,以致于占据了数据结构的半壁江山.STL中大名顶顶的关联容器--集合(set).映射(map)便是使用二叉树实现 ...

  2. Leetcode 笔记 99 - Recover Binary Search Tree

    题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...

  3. Leetcode 笔记 98 - Validate Binary Search Tree

    题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...

  4. Leetcode: Convert sorted list to binary search tree (No. 109)

    Sept. 22, 2015 学一道算法题, 经常回顾一下. 第二次重温, 决定增加一些图片, 帮助自己记忆. 在网上找他人的资料, 不如自己动手. 把从底向上树的算法搞通俗一些. 先做一个例子: 9 ...

  5. [LeetCode] Closest Binary Search Tree Value II 最近的二分搜索树的值之二

    Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...

  6. [LeetCode] Closest Binary Search Tree Value 最近的二分搜索树的值

    Given a non-empty binary search tree and a target value, find the value in the BST that is closest t ...

  7. [LeetCode] Verify Preorder Sequence in Binary Search Tree 验证二叉搜索树的先序序列

    Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary ...

  8. [LeetCode] Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最小共同父节点

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...

  9. [LeetCode] Binary Search Tree Iterator 二叉搜索树迭代器

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...

随机推荐

  1. Apache MINA 框架之Handler介绍

    IoHandler 具备以下几个功能: sessionCreated sessionOpened sessionClosed sessionIdle exceptionCaught messageRe ...

  2. 请输出in.txt文件中的2 4 6 8 9 10 12行

    in.txt文件: 学号 姓名 性别 年龄 1001 张三 男 18 1002 赵四 男 19 1003 李丽 女 18 1004 刘芳 女 32 1005 王五 男 54 1006 小明 男 32 ...

  3. .NET通信中的同步和异步处理

    同步与异步的概念: .NET中的通信数据处理有同步和异步之分,我理解的同步过程是接收端接收数据,如果数据没有过来,就一直等着(阻塞过程),直到有数据传送过来可以接收,接下来程序才继续向下进行:异步过程 ...

  4. qq第3方登录的JS实现方式记录

    首先申请qq第3方登录接入的appkey和appid,具体方式http://wiki.connect.qq.com/%E5%87%86%E5%A4%87%E5%B7%A5%E4%BD%9C_oauth ...

  5. js关于闭包的内存的问题--deep down

    js有一个东西叫做GC(garbage collection )垃圾回收机制;js中有两种类型:js基本数据类型,js引用类型; 当一个函数[对象]--引用类型被引用后,过后,出了它的功能之后,gc会 ...

  6. My.Ioc 代码示例——实现自动注册/解析

    在很多 Ioc 容器中,当使用者向容器请求实现了某个契约类型 (Contract Type) 的服务时 (调用类似如下方法 container.Resolve(Type contractType)), ...

  7. C#异常处理表、类、SQL

    表SQL /****** Object: Table [dbo].[IError] Script Date: 09/05/2012 17:00:41 ******/ SET ANSI_NULLS ON ...

  8. jrae源码解析(一)

    jare用java实现了论文<Semi-Supervised Recursive Autoencoders for Predicting Sentiment Distributions>中 ...

  9. 【转】 NSArray copy 问题

    转自:   http://blog.sina.com.cn/s/blog_6b1e4a060102uz0i.html   好久没写博客了,今天看到同事的代码中用到了 copy 这个 方法,之前也有了解 ...

  10. cas sso原理(转)

    采用CAS原理构建单点登录 企业的信息化过程是一个循序渐进的过程,在企业各个业务网站逐步建设的过程中,根据各种业务信息水平的需要构建了相应的应用系统,由于这些应用系统一般是 在不同的时期开发完成的,各 ...