-
Notifications
You must be signed in to change notification settings - Fork 271
Expand file tree
/
Copy pathLinearSearchSentinel.c
More file actions
47 lines (39 loc) · 1.3 KB
/
LinearSearchSentinel.c
File metadata and controls
47 lines (39 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
* Exemplo de Busca Sentinela em C
* Objetivo: Encontrar um valor em um vetor sem precisar testar todos os
*valores dentro do laço
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define TAM_VETOR 10
// Busca sentinela, realiza uma busca sequencial sem precisar testar a chave a
// cada passo do laço de busca
int buscaSentinela(int vetor[], int chave) {
vetor[TAM_VETOR] =
chave; // Coloca o valor buscado (chave) na última posição do vetor
int aux = 0; // Variável de controle do laço
while (vetor[aux] !=
chave) // Enquanto não encontrar o valor (chave) incrementa 1 em aux
aux++;
if (aux == TAM_VETOR)
return -1;
return aux;
}
int main() {
int vetor[TAM_VETOR + 1]; // Declara o vetor com +1 pois é a posição que será
// utilizada pela sentinela
// Preenche o vetor com valores aleatórios 0-1000
srand(time(NULL));
for (int i = 0; i < TAM_VETOR; i++) {
vetor[i] = rand() % 1000;
printf("%d, ", vetor[i]);
}
// Faz a busca, passando como parâmetro o vetor e a chave que deseja buscar
int res = buscaSentinela(vetor, vetor[TAM_VETOR - 2]);
if (res != -1)
printf("\n\nValor %d encontrado na posicao %d.\n\n", vetor[res], res);
else
printf("\n\nValor não encontrado no vetor\n\n");
return 0;
}