|
1 | 1 | # frozen_string_literal: true
|
| 2 | +def sentinel_search(value, array) |
| 3 | + # Create a copy of the array |
| 4 | + array_copy = array.dup |
2 | 5 |
|
3 |
| -def busca_sentinela(valor, vetor) |
4 |
| - # Adiciona o valor ao final do vetor |
5 |
| - vetor.push(valor) |
6 |
| - indice = 0 |
| 6 | + # Add the value to the end of the array copy |
| 7 | + array_copy.push(value) |
| 8 | + index = 0 |
7 | 9 |
|
8 |
| - # Enquanto nao for o valor, incrementa 1 |
9 |
| - indice += 1 while vetor[indice] != valor |
| 10 | + # While it's not the value, increment by 1 |
| 11 | + index += 1 while array_copy[index] != value |
10 | 12 |
|
11 |
| - # Remove o valor do final do vetor |
12 |
| - vetor.pop |
| 13 | + # Remove the value from the end of the array copy |
| 14 | + array_copy.pop |
13 | 15 |
|
14 |
| - # Se a variavel indice corresponde ao tamanho do vetor, retorne -1 |
15 |
| - return -1 if indice == vetor.length |
| 16 | + # If the index variable equals the array size, return -1 |
| 17 | + return -1 if index == array_copy.length |
16 | 18 |
|
17 |
| - # Caso contrario, retorne a posicao do valor no vetor |
18 |
| - indice |
| 19 | + # Otherwise, return the position of the value in the array copy |
| 20 | + index |
19 | 21 | end
|
20 | 22 |
|
21 |
| -vetor = [1, 4, 5, 2, 42, 34, 54, 98, 89, 78, 67] |
22 |
| -puts busca_sentinela(98, vetor) |
| 23 | +array = [1, 4, 5, 2, 42, 34, 54, 98, 89, 78, 67] |
| 24 | +puts sentinel_search(98, array) |
0 commit comments