정렬이 안되어 있을 때
arr = [5, 7, 8, 6, 3, 2, 1, 4, 9]
n = len(arr)
def search(target):
for i in range(n):
if arr[i] == target:
return i
return -1
print(search(1))
arr = [5, 7, 8, 6, 3, 2, 1, 4, 9]
def search(target):
i = 0
while i < n and arr[i] != target:
i += 1
if arr[i] == target:
return i
return -1
print(search(1))
정렬이 되어 있을 때
arr = [1, 2, 3, 5, 8, 9, 11, 13, 14]
n = len(arr)
def search(target):
for i in range(n):
if arr[i] == target:
return i
return -1
print(search(8))
arr = [1, 2, 3, 5, 8, 9, 11, 13, 14]
n = len(arr)
def search(target):
i = 0
while i < n and arr[i] <= target:
if arr[i] == target:
return i
i += 1
return -1
print(search(8))