Binary Search

Desktop

Binary Search


版权声明:本文为 cheng-zhi 原创文章,可以随意转载,但必须在明确位置注明出处!

Binary Search is a basic search algorithm. Its basic idea is each search is reduced by half of the data. Such as,using Binary Search to search 2 in this table :

1. First  search index = (0 + 10) / 2 = 5,and 2 < 5,then search [0, 4]
2. Second search index = (0 + 4)  / 2 = 2, and 2 == 2,find it !

Before you use Binary Search,you must be know below points :

1. Binary Search O(n) = O(log2n)
2. The set of searchs it must be ordered(Ascending or Descneding),such as above array table. 
3. It applies to infrequently changing and finding frequent ordered lists.

Now,we see the algorithm code.

Algorithm Code

I use C to coding,like below :

Array and division

Using arrays and division is the easiest way :

int *binary_search_common(int *array, int length, int key) {
  int low = 0;
  int mid = 0;
  int high = length - 1;

  while (low <= high) {
    mid = (high + low) / 2;
    printf("binary_search_common: mid = %d\n", mid);

    if (key < array[mid])
      high = mid - 1;
    else if (key > array[mid])
      low = mid + 1;
    else 
      return array + mid;   // Ok,find it !
  }

  // No find !
  return NULL;
}

Point and right shift

Using pointer and right shift instead of array and division to improve efficiency :

int *binary_search_improve(int *array, int length, int key) {
  int *low = array;
  int *mid = NULL;
  int *high = array + length - 1;

  while (low <= high) {
    mid = low + ((high - low) >> 1);
    printf("binary_search_improve: mid = %d\n", mid - low);

    if (key < *mid)
      high = mid - 1;
    else if (key > *mid)
      low = mid + 1;
    else 
      return mid;   // Ok,find it !
  }
  
  // No find !
  return NULL;
}

Recursive

I suggest you`d better use recursion to achieve it again :

int *binary_search_rec(int *array, int *low, int *high, int key) {
  if (low > high) 
    return NULL;    // No find !

  int *mid = low + ((high - low) >> 1);
  printf("binary_search_rec: mid = %d\n", mid - low);

  if (key < *mid)
    return binary_search_rec(array, low, mid - 1, key);
  else if (key > *mid)
    return binary_search_rec(array, mid + 1, high, key);
  else
    return mid; // Ok,find it !
}

TestCode

I use an order array as test data :

int main(int argc, char **argv) {
  if (argc < 2) {
    printf("Usage: ./a.out search_num:[0, 10]\n");
    exit(1);
  }

  int a[11] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  int key = atoi(argv[1]);
   
  int *find1 = binary_search_common(a, 11, key); 
  int *find2 = binary_search_improve(a, 11, key); 
  int *find3 = binary_search_rec(a, a, a + 11, key);
  
  printf("%d\n", *find1);
  printf("%d\n", *find2); 
  printf("%d\n", *find3);
  return 0;
}

Compile and run :

gcc binary_search.c
./a.out 2

binary_search_common: mid = 5
binary_search_common: mid = 2
binary_search_improve: mid = 5
binary_search_improve: mid = 2
binary_search_rec: mid = 5
binary_search_rec: mid = 2
2
2
2

Can be seen,we only need to find 2 times. But,for an ordered list,it is not the fastest algorithm. For example,finding 2 still takes 2 times,but actually we can find 2 only once !

Continue to see the faster algorithm below !

Interpolation Search

Interpolation Search and Binary Search basically the same,the only difference is how to calculate mid.

In Binary Search :

mid = low + ((high - low) >> 1);

But in Interpolation Search :

mid = low + (high - low) * ((double)(key - array[low]) / (array[high] - array[low]));

What is it ? look below :

We calculate the mid by the following proportional formula :

(mid - low) / (high - low) = (key - array[low]) / (array[high] - array[low])

->

mid = low + (high - low) * (key - array[low]) / (array[high] - array[low]);

But we must be add double to case type,because we need to let 0 < (key - array[low]) / (array[high] - array[low]) < 1if we do not case it to double,the expression will be zeor,so we must be case it to double :

// Case (key - array[low]) to double.
mid = low + (high - low) * ((double)(key - array[low]) / (array[high] - array[low]));

Point type,because point do not add to double,we need to case it to int so that it can add to point low :

mid = low + (int)((high - low) * ((double)(key - (*low)) / ((*high) - (*low))));

Interpolation Code

OK,now you only need to replace how to calculate the expression of mid can be achieved Interpolation Search :

int *binary_search_xxx(int *array, int length, int key) {
  ...
  while (low <= high) {
    // For array and division.
    mid = low + (high - low) * ((double)(key - array[low]) / (array[high] - array[low]));
    printf("binary_search_xxx: mid = %d\n", mid);

    // For point and >>
    mid = low + (int)((high - low) * ((double)(key - (*low)) / ((*high) - (*low))));
    printf("binary_search_xxx: mid = %d\n", mid - low);
  }
  ...
}

You can use the above code main function to test this algorithm,and the result like below :

gcc binary_search.c
./a.out 2

binary_search_common: mid = 2   // Note: We only need to search once !
binary_search_improve: mid = 2
binary_search_rec: mid = 2
2
2
2

This can be,thank you for reading.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,590评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,808评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,151评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,779评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,773评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,656评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,022评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,678评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,038评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,756评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,411评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,005评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,973评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,053评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,495评论 2 343

推荐阅读更多精彩内容

  • “孩子作业写的太慢,拖拖拉拉,磨磨蹭蹭,总是不能按时完成。” “即使你坐在他旁边,盯着他写,一笔一划指导他写,天天...
    俩千金的妈阅读 299评论 0 0
  • 17:43分,我说:大头,晚上你们家门口麻辣烫。她说:好,我等你。 结果,我坐着车晃晃悠悠走了一个...
    木兮日记阅读 126评论 0 3
  • 题记:小王子曾说过:“生活才不是生命荒唐的编号,生活的意义在于生活本身。”只要活着,就能体验到生命每个阶段不同的精...
    蓝色的海sunshine阅读 325评论 0 0
  • 作为一个N*N线不知名小写手,我曾经多次在微博上写过奇葩说,更有好几篇文章的取材来源于这个节目的辩题。我毫不掩饰地...
    维真阅读 4,373评论 1 11