有一个有序表为(1,3,9,12,32,41,45,62,75,77,82,95,99),当采用折半查找法查找关键字为82的元素时,______ 次比较后查找成功。
A. 1
B. 2
C. 4
D. 8
left
right
left = 0
right = n-1
n
mid = (left + right) / 2
arr[mid]
target
arr[mid] == target
mid
arr[mid] > target
right = mid - 1
arr[mid] < target
left = mid + 1
left > right
有序表为 (1, 3, 9, 12, 32, 41, 45, 62, 75, 77, 82, 95, 99),查找关键字为82的元素。
(1, 3, 9, 12, 32, 41, 45, 62, 75, 77, 82, 95, 99)
right = 12
mid = (0 + 12) / 2 = 6
arr[6] = 45
45 < 82
left = 7
mid = (7 + 12) / 2 = 9
arr[9] = 77
77 < 82
left = 10
mid = (10 + 12) / 2 = 11
arr[11] = 95
95 > 82
right = 10
mid = (10 + 10) / 2 = 10
arr[10] = 82
82 == 82
因此,查找关键字为82的元素需要4次比较。
折半查找左少右多
C
用户登录可进行刷题及查看答案
登录后提交答案