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);
    

      

  • 相关阅读:
    LeetCode "Median of Two Sorted Arrays"
    LeetCode "Distinct Subsequences"
    LeetCode "Permutation Sequence"

    LeetCode "Linked List Cycle II"
    LeetCode "Best Time to Buy and Sell Stock III"
    LeetCode "4Sum"
    LeetCode "3Sum closest"
    LeetCode "3Sum"
    LeetCode "Container With Most Water"
  • 原文地址:https://www.cnblogs.com/magic_evan/p/3120991.html
Copyright © 2011-2022 走看看