How to merge two ordered arrays by python
This article mainly explains how python merges two ordered arrays. Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "Python how to merge two ordered arrays"!
Merge two ordered sequences
Write a binary search algorithm
Known function prototypes:
def binary_search(arr,left,right,hkey):
pass
Ask to complete the above code
Notes:
(left+right) //2, better written: left + (right-left)//2 iteration, must pay attention to while judging the code of equal sign problem binary search is still easy to write bug iteration binary search
Code Reference Starmate Leven:
def binary_search(arr,left,right,hkey):
while left hkey: #strictly greater than
right = mid - 1
else: #Here strictly less than
left = mid + 1
return -1 #means not found.
if __name__ == "__main__":
sorted_list = [1,2,3,4,5,6,7,8]
result = binary_search(sorted_list,0,7,4)
print(result) recursive binary search def binary_search(arr,left,right,hkey):
if len(arr) == 0:
return -1
if left > right:
return -1
mid = left + (right-left) // 2
if arr[mid] == hkey:
return mid
elif arr[mid] < hkey: #strictly less than
return binary_search(arr,mid+1,right,hkey) #
else:
return binary_search(arr,left,mid-1,hkey)
if __name__ == "__main__":
sorted_list = [1,2,3,4,5,6,7,8]
result = binary_search(sorted_list,0,7,4)
print(result) More Demo Animations
Key codes can be found:
Key not found:
Merge two ordered arrays left and right:
def merge(left,right):
#Code completion
#
return temp
The idea can refer to the schematic diagram:
At this point, I believe that everyone has a deeper understanding of "how python merges two ordered arrays", so let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!