zoukankan      html  css  js  c++  java
  • 二分查找算法

    1、已经排序的数组,查找索引最小的值:

    int binary_search(int[] array, int n, int value)
    {
        int maxIndex = n;
        int minIndex = 1;
        int index;
        while (maxIndex >= minIndex)
        {
            index = (maxIndex + minIndex) / 2;
            if (array[index - 1] == value)
            {
                while (--index > 0)
                {
                    if (array[index - 1] == value) continue;
                    break;
                }
                return index;
            }
            if (array[index - 1] > value)
            {
                maxIndex = index - 1;
                continue;
            }
            if (array[index - 1] < value)
            {
                minIndex = index + 1;
                continue;
            }
        }
        return -1;
    }
    

      调用方法:

    int index = binary_search(new[] { 1 }, 1, 1);
    index = binary_search(new[] { 1 }, 1, 2);
    index = binary_search(new[] { 1, 2 }, 2, 2);
    index = binary_search(new[] { 1, 2 }, 2, 1);
    index = binary_search(new[] { 1, 2 }, 2, 3);
    index = binary_search(new[] { 1, 2, 3 }, 3, 2);
    index = binary_search(new[] { 1, 2, 3 }, 3, 3);
    index = binary_search(new[] { 1, 2, 3 }, 3, 1);
    index = binary_search(new[] { 1, 2, 3 }, 3, 4);
    index = binary_search(new[] { 1, 2, 3, 3, 3, 3, 3, 4 }, 8, 3);
    index = binary_search(new[] { 1, 2, 3, 4 }, 4, 4);
    index = binary_search(new[] { 1, 2, 3, 4 }, 4, 2);
    index = binary_search(new[] { 1, 2, 3, 4 }, 4, 1);
    index = binary_search(new[] { 1, 2, 3, 4 }, 4, 5);
    

      

  • 相关阅读:
    tp5 thinkphp5 伪静态修改 fastadmin
    ThinnkPHP内置视图循环语句
    PHP禁止重写策略
    冒泡排序
    Ruby--正则
    JS正则
    JS禁止父元素事件
    Rails--default_scope
    公网映射
    查企业情况和招聘的网站
  • 原文地址:https://www.cnblogs.com/magic_evan/p/3120991.html
Copyright © 2011-2022 走看看