二分查找算法不同语言实现

二分查找

二分查找时间复杂度: O ( l o g n ) O(logn) O(logn)

直接上代码

Java:

public class BinarySearch {
    
    

    // has to return boxed integer in order to comfort to interface defined in the book
    private static Integer binarySearch(int[] list, int item) {
    
    
        int low = 0;
        int high = list.length - 1;

        while (low <= high) {
    
    
            int mid = (low + high) / 2;
            int guess = list[mid];
            if (guess == item) {
    
    
                return mid;
            }
            if (guess > item) {
    
    
                high = mid - 1;
            } else {
    
    
                low = mid + 1;
            }
        }

        return null;
    }

    public static void main(String[] args) {
    
    
        int[] myList = {
    
    1, 3, 5, 7, 9};

        System.out.println(binarySearch(myList, 3)); // 1
        System.out.println(binarySearch(myList, -1)); // null
    }
}

C:

#include <stdio.h>

int binarySearch(int[], int, int);

int main()
{
    
    
    int myList[] = {
    
    1, 3, 5, 7, 9};
    int len = sizeof(myList) / sizeof(myList[0]);

    printf("%d\n", binarySearch(myList, 3, len));  // 1
    printf("%d\n", binarySearch(myList, -1, len)); //-1
    return 0;
}

int binarySearch(int list[], int item, int len)
{
    
    
    int low = 0;
    int high = len;
    while (low <= high)
    {
    
    
        int mid = (low + high)/2; 
        int guess = list[mid];

        if (guess == item)
        {
    
    
            return mid;
        }
        else if (guess > item)
        {
    
    
            high = mid - 1;
        }
        else
        {
    
    
            low = mid + 1;
        }
    }
    return -1; //number not found
}

C++:

#include "iostream"
using namespace std;

void binarySearch(int data_array[], int element, int len)
{
    
    
    int low = 0;
    int high = len;
    while (low <= high)
    {
    
    
        int mid = (low + high)/2; 
        int guess = data_array[mid];

        if (guess == element)
        {
    
    
            cout<<"Element found at "<<mid<<" th index"<<endl ;
            return ;
        }
        else if (guess > element)
        {
    
    
            high = mid - 1;
        }
        else
        {
    
    
            low = mid + 1;
        }
    }
    cout<<"Element Not Found"<<endl ;
    return ; //number not found
}
int main()
{
    
    
    int data_array[] = {
    
    2,10,23,44,100,121};
    int length = sizeof(data_array) / sizeof(int);

    binarySearch(data_array, 3, length) ;  // not found case
    binarySearch(data_array, 2, length) ; // found at corner case
    binarySearch(data_array, 44, length) ; //found at middle case
    return 0;
}

Python:

class BinarySearch():

  def search_iterative(self, list, item):
    # low and high keep track of which part of the list you'll search in.
    low = 0
    high = len(list) - 1

    # While you haven't narrowed it down to one element ...
    while low <= high:
      # ... check the middle element
      mid = (low + high) // 2
      guess = list[mid]
      # Found the item.
      if guess == item:
        return mid
      # The guess was too high.
      if guess > item:
        high = mid - 1
      # The guess was too low.
      else:
        low = mid + 1

    # Item doesn't exist
    return None

  def search_recursive(self, list, low, high, item):
    # Check base case 
    if high >= low: 
  
        mid = (high + low) // 2
        guess = list[mid]
  
        # If element is present at the middle itself 
        if guess == item:
            return mid 
  
        # If element is smaller than mid, then it can only 
        # be present in left subarray 
        elif guess > item: 
            return self.search_recursive(list, low, mid - 1, item) 
  
        # Else the element can only be present in right subarray 
        else: 
            return self.search_recursive(list, mid + 1, high, item) 
  
    else: 
        # Element is not present in the array 
        return None

if __name__ == "__main__":
  # We must initialize the class to use the methods of this class
  bs = BinarySearch()
  my_list = [1, 3, 5, 7, 9]
  
  print(bs.search_iterative(my_list, 3)) # => 1

  # 'None' means nil in Python. We use to indicate that the item wasn't found.
  print(bs.search_iterative(my_list, -1)) # => None

猜你喜欢

转载自blog.csdn.net/qq_44033208/article/details/128493193