Skip to content

Commit d22c92c

Browse files
authored
Add files via upload
1 parent a16bb54 commit d22c92c

2 files changed

Lines changed: 16 additions & 15 deletions

File tree

‎Searching/Binary_Search.py‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,22 @@
11
def binary_search(arr:list[int],target:int,low:int,high:int)->int:
2+
# 二分搜尋:在已排序陣列 arr 中尋找 target,搜尋範圍為 low 到 high
23
if low<=high:
3-
mid=(low+high)//2
4-
if arr[mid]==target:
5-
return mid
6-
elif arr[mid]<target:
7-
return binary_search(arr,target,mid+1,high)
4+
middle=(low+high)//2 # 取得中間索引
5+
if arr[middle]==target:# if中間值等於目標
6+
return middle # 回傳index
7+
elif arr[middle]<target: # 若中間值小於目標
8+
return binary_search(arr,target,middle+1,high) # 往右半部遞迴搜尋
89
else:
9-
return binary_search(arr,target,low,mid-1)
10+
return binary_search(arr,target,low,middle-1) # 往左半部遞迴搜尋
1011
else:
1112
return -1
1213
#main function to test the binary_search function
1314
if __name__=="__main__":
1415
arr=[1,7,13,15,20,50]
15-
target=15
16+
target=15 #target:要搜尋的目標
1617
print("Binary Search")
17-
result=binary_search(sorted(arr),target,0,len(arr)-1)
18+
result=binary_search(sorted(arr),target,0,len(arr)-1) #執行二分搜尋
1819
if result!=-1:
19-
print(f"Found element at index {result}")
20+
print(f"Found element at index {result}") # 找到則輸出索引
2021
else:
2122
print("Not found")

‎Searching/Linear_Search.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
from typing import List
22
def linear_search(arr:list[int],target:int)->int:
3-
for i in range(len(arr)):
4-
if arr[i]==target:
5-
return i
3+
for i in range(len(arr)): # 線性搜尋:逐一檢查陣列中的每個元素是否等於目標值
4+
if arr[i]==target: # 如果找到目標值
5+
return i # 回傳該元素的index
66
return -1
77
#main function to test the linear_search function
88
if __name__=="__main__":
99
arr=[1,7,13,15,20,50]
10-
target=7
10+
target=7 # 要搜尋的目標值
1111
print("Linear Search")
12-
result=linear_search(arr,target)
12+
result=linear_search(arr,target) # 執行線性搜尋
1313
if result!=-1:
14-
print(f"Element at index {result}")
14+
print(f"Element at index {result}") # 找到則輸出索引
1515
else:
1616
print("Element not found.")

0 commit comments

Comments
 (0)