int iteratorBinarySearchList extends Comparable super T list T key int low = 0; int high = listsize-1; ListIterator extends Comparable super T i = listlistIterator; while low = high
这段代码实现了一个使用迭代器进行二分查找的方法。它接受一个实现了Comparable接口的泛型列表和一个要查找的关键字。
首先,将列表的边界设置为low和high,分别为0和列表长度减1。
然后,创建一个列表迭代器i来遍历列表。
然后,使用while循环进行二分查找。在每次循环中,计算中间索引mid,将列表中的元素[mid]与关键字进行比较,并将比较结果存储在cmp变量中。
如果cmp小于0,说明关键字在mid的右侧,将low更新为mid + 1。
如果cmp大于0,说明关键字在mid的左侧,将high更新为mid - 1。
如果cmp等于0,说明找到了关键字,返回mid作为结果。
如果循环结束后仍然没有找到关键字,返回-(low + 1)作为结果,表示关键字不存在于列表中。
原文地址: https://www.cveoy.top/t/topic/hTjq 著作权归作者所有。请勿转载和采集!