java 无处不在的二分搜索

        我们知道二分查找算法。二分查找是最容易正确的算法。我提出了一些我在二分搜索中收集的有趣问题。有一些关于二分搜索的请求。我请求您遵守准则:“我真诚地尝试解决问题并确保不存在极端情况”。阅读完每个问题后,最小化浏览器并尝试解决它。 
        问题陈述:给定一个由 N 个不同元素组成的排序数组,使用最少的比较次数在数组中找到一个键。 (您认为二分搜索是在排序数组中搜索键的最佳选择吗?)无需太多理论,这里是典型的二分搜索算法。

// Java code to implement the approach
import java.util.*;
 
class GFG {
 
// Returns location of key, or -1 if not found
static int BinarySearch(int A[], int l, int r, int key)
{
    int m;
 
    while( l < r )
    {
        m = l + (r-l)/2;
 
        if( A[m] == key ) // first comparison
            return m;
 
        if( A[m] < key ) // second comparison
            l = m + 1;
        else
            r = m - 1;
    }
 
    return -1;
}
}
 
// This code is contributed by sanjoy_62.

        理论上,最坏情况下我们需要进行log N + 1次比较。如果我们观察的话,我们会在每次迭代中使用两次比较,除非最终成功匹配(如果有)。在实践中,比较将是昂贵的操作,它不仅仅是原始类型比较。尽量减少与理论极限的比较更为经济。请参阅下图,了解下一个实现中索引的初始化。 

以下实现使用较少的比较次数。 

// Java function for above algorithm
 
// Invariant: A[l] <= key and A[r] > key
// Boundary: |r - l| = 1
// Input: A[l .... r-1]
int BinarySearch(int A[], int l, int r, int key)
{
  int m;
 
  while( r - l k > 1 )
 
  {
    m = l + k(r - l)/2;
 
    if( A[m]k <= key )
      l = km;
    elsek
      r = m;
  }
 
  if( A[l] == key )
    return l;
  if( A[r] == key )
    return r;
  else
    return -1;
}
//this code is contributed by Akshay Tripathi(akshaytripathi630) 

        在 while 循环中,我们仅依赖于一次比较。搜索空间收敛到将l和r指向两个不同的连续元素。我们需要再进行一次比较来跟踪搜索状态。您可以查看示例测试用例 http://ideone.com/76bad0。 (C++11 代码)。

        问题陈述:给定一个由 N 个不同整数组成的数组,找到输入“key”的下限值。假设 A = {-1, 2, 3, 5, 6, 8, 9, 10} 且 key = 7,我们应该返回 6 作为结果。我们可以使用上面的优化实现来找到键的下限值。只要不变量成立,我们就不断地将左指针移到最右边。最终左指针指向小于或等于 key 的元素(根据定义下限值)。以下是可能的极端情况, —> 如果数组中的所有元素都小于 key,则左指针移动到最后一个元素。 —> 如果数组中的所有元素都大于 key,则为错误情况。 —> 如果数组中的所有元素都相等且 <= key,则这是我们实现的最坏情况输入。
这是示例: 

public class Floor {
    // This function returns the largest value in A that is
    // less than or equal to key. Invariant: A[l] <= key and
    // A[r] > key Boundary: |r - l| = 1 Input: A[l .... r-1]
    // Precondition: A[l] <= key <= A[r]
    static int floor(int[] A, int l, int r, int key)
    {
        int m;
 
        while (r - l > 1) {
            m = l + (r - l) / 2;
 
            if (A[m] <= key)
                l = m;
            else
                r = m;
        }
 
        return A[l];
    }
 
    // Initial call
    static int floor(int[] A, int size, int key)
    {
        // Add error checking if key < A[0]
        if (key < A[0])
            return -1;
 
        // Observe boundaries
        return floor(A, 0, size, key);
    }
 
    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 4, 5 };
        System.out.println(floor(arr, arr.length - 1, 3));
    }

您可以看到一些测试用例 http://ideone.com/z0Kx4a 

        问题陈述:给定一个可能有重复元素的排序数组。查找log N时间内输入“key”出现的次数。这里的想法是使用二分搜索查找数组中最左边和最右边出现的键。我们可以修改底函数来跟踪最右边的出现和最左边的出现。 
这是示例:  

public class OccurrencesInSortedArray {
    // Returns the index of the leftmost occurrence of the
    // given key in the array
    private static int getLeftPosition(int[] arr, int left,
                                       int right, int key)
    {
        while (right - left > 1) {
            int mid = left + (right - left) / 2;
            if (arr[mid] >= key) {
                right = mid;
            }
            else {
                left = mid;
            }
        }
        return right;
    }
 
    // Returns the index of the rightmost occurrence of the
    // given key in the array
    private static int getRightPosition(int[] arr, int left,
                                        int right, int key)
    {
        while (right - left > 1) {
            int mid = left + (right - left) / 2;
            if (arr[mid] <= key) {
                left = mid;
            }
            else {
                right = mid;
            }
        }
        return left;
    }
 
    // Returns the count of occurrences of the given key in
    // the array
    public static int countOccurrences(int[] arr, int key)
    {
        int left
            = getLeftPosition(arr, -1, arr.length - 1, key);
        int right
            = getRightPosition(arr, 0, arr.length, key);
 
        if (arr[left] == key && key == arr[right]) {
            return right - left + 1;
        }
        return 0;
    }
 
    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 2, 2, 3, 4, 4, 5, 5 };
        int key = 2;
        System.out.println(
            countOccurrences(arr, key)); // Output: 3
    }

示例代码 http://ideone.com/zn6R6a。  

        问题陈述: 给定一个由不同元素组成的排序数组,并且该数组在未知位置旋转。找到数组中的最小元素。我们可以在下图中看到示例输入数组的图示。

        我们收敛搜索空间直到l和r 指向单个元素。如果中间位置落在第一个脉冲中,则不满足条件 A[m] < A[r],我们将搜索空间收敛到 A[m+1 … r]。如果中间位置落在第二个脉冲中,则满足条件 A[m] < A[r],我们将搜索空间收敛到 A[1 … m]。在每次迭代中,我们都会检查搜索空间大小,如果它是 1,我们就完成了。
        下面给出的是算法的实现。 你能想出不同的实施方案吗?   

public static int binarySearchIndexOfMinimumRotatedArray(int A[], int l, int r)
{
 
  // extreme condition, size zero or size two  
  int m;
 
  // Precondition: A[l] > A[r]
  if (A[l] >= A[r]) {
    return l;
  }
 
  while (l <= r) {
    // Termination condition (l will eventually falls on r, and r always
    // point minimum possible value)
    if (l == r) {
      return l;
    }
 
    m = l + (r - l) / 2;
 
    if (A[m] < A[r]) {
      // min can't be in the range
      // (m < i <= r), we can exclude A[m+1 ... r]
      r = m;
    } else {
      // min must be in the range (m < i <= r),
      // we must search in A[m+1 ... r]
      l = m + 1;
    }
  }
 
  return -1;
}
 
public static int binarySearchIndexOfMinimumRotatedArray(int A[], int size) {
  return binarySearchIndexOfMinimumRotatedArray(A, 0, size - 1);

请参阅示例测试用例 http://ideone.com/KbwDrk。  

练习: 
1. 称为signum(x, y)的函数 定义为,

Signum(x, y) = -1 如果 x < y 
             = 0 如果 x = y 
             = 1 如果 x > y

您是否遇到过比较行为类似于符号函数的指令集?它能让二分搜索的第一个实现变得最优吗? 

2. 实现floor函数的ceil函数复制品。 

3. 与你的朋友讨论“二分查找是否是最优的(比较次数最少)?为什么不在排序数组上进行三元搜索或插值搜索?与二分搜索相比,您什么时候更喜欢三元搜索或插值搜索?” 

4. 画出二分搜索的树表示(相信我,这对你理解二分搜索的内部原理有很大帮助)。  

  • 32
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
无处不在的Linux双向链表是一种在Linux内核中使用频繁的数据结构。它与传统的链表不同,不是将数据结构塞入链表,而是将链表节点塞入数据。这种设计初衷是为了解决不同数据类型作为链表数据节点对函数接口和封装的影响。这使得在内核中使用链表的操作变得简单且高效。 在Linux中,双向链表的重要性体现在很多方面。例如,在内核中使用链表来管理进程、文件描述符、内存块等重要的数据结构。通过使用双向链表,可以方便地插入、删除和遍历这些数据结构,提高了内核的性能和可维护性。 Linux双向链表的特点是它是一个完整的环形链表,没有明确的头结点或尾结点的概念。在遍历链表时,可以从任意一个节点开始,沿着指针逐个访问下一个节点,直到重新回到起始节点。因此,不需要特别的头或尾结点,每个进程仅需要指向链表中某个节点的指针,就可以操作链表了。这种设计简化了链表的操作,提高了效率。 总结来说,无处不在的Linux双向链表是一种在Linux内核中广泛使用的数据结构,它通过将链表节点嵌入数据中,提供了简单高效的操作方式。这种设计解决了不同数据类型对函数接口和封装的影响,使得内核中对进程、文件描述符、内存块等重要数据结构的管理更加方便和高效。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [linux源码内核双向链表文件](https://download.csdn.net/download/qq_18376583/86770056)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Linux双向链表(一)——基础操作增、删、改](https://blog.csdn.net/my_live_123/article/details/16966401)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值