“Pencarian biner rekursif” Kode Jawaban

Pencarian biner rekursif

int binarySearch(int[] A, int low, int high, int x)
{
    if (low > high) {
        return -1;
    }
    int mid = (low + high) / 2;
    if (x == A[mid]) {
        return mid;
    }
    else if (x < A[mid]) {
        return binarySearch(A, low,  mid - 1, x);
    }
    else {
        return binarySearch(A, mid + 1,  high, x);
    }
}
Friendly Falcon

C, Rekursif Pencarian Biner

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int ret = 0;
		
        if (nums.size() == 0)
            return -1;
  
        if (nums[nums.size()/2] < target) {
            vector<int> halfVec(nums.begin()+nums.size()/2+1,nums.end());
            auto retIdx = search(halfVec,target);
            if (retIdx == -1) return -1;
            ret += retIdx +  nums.size()/2+1;
        } else if (nums[nums.size()/2] > target) {
            vector<int> halfVec(nums.begin(),nums.begin()+nums.size()/2);
            ret = search(halfVec,target);
        } else {
            ret = nums.size()/2;
        }
         
        return ret;
        
    }
};
Mib

Kode pencarian biner rekursif

# Code recursive binary search.
def binarySearchAlgorithm(arr, l, r, x):
	if r >= l:
		mid = l + (r - l) 
		if arr[mid] == x:
			return mid
		elif arr[mid] > x:
			return binarySearch(arr, l, mid-1, x)
		else:
			return binarySearch(arr, mid + 1, r, x)
	else:
		return -1
arr = [3, 43, 56, 96]
find = 56
result = binarySearchAlgorithm(arr, 0, len(arr)-1, find)
if result != -1:
	print("Element is present at index % d" % result)
else:
	print("Element is not present in array")
Outrageous Ostrich

Jawaban yang mirip dengan “Pencarian biner rekursif”

Pertanyaan yang mirip dengan “Pencarian biner rekursif”

Lebih banyak jawaban terkait untuk “Pencarian biner rekursif” di C++

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya