✅ The verified answer to this question is available below. Our community-reviewed solutions help you understand the material better.
Suponha uma classe SomeClass onde está definida uma variável \tiny a[size]
1 template<int size=10>
2 class SomeClass {
3 public:
4 ...
5 int binSearch(int key);
6 private:
7 int length;
8 int a[size];
9 };
Considere o seguinte método binSearch() dessa classe
12 // Efectua uma pesquisa binária por uma chave numa array.
13 // Pré-condição: A array a[0]...a[a.length-1] está ordenada
14 // por ordem ascendente.
15 // Pós-condição: Devolve index tal que a[index] == key.
16 // Se key não está em v, então devolve -1.
17
18 template<int size>
19 int SomeClass<size>::binSearch(int key)
20 {
21 int low = 0;
22 int high = length - 1;
23 while (low <= high)
24 {
25 int mid = (low + high)/2;
26 if (a[mid] == key)
27 return mid;
28 elseif (a[mid] < key)
29 low = mid + 1;
30 else
31 high = mid - 1;
32 }
33 return -1;
34 }
A pesquisa binária será efectuada na seguinte lista
Na procura pelo elemento 27, o intervalo de pesquisa depois da primeira passagem pelo ciclo while, será