BUPT-homework/semester1/pset9/2-search.c

61 lines
1.1 KiB
C
Raw Permalink Normal View History

2021-11-25 16:13:12 +08:00
#include <stdio.h>
int maxnum = -2147483648;
void mkhashtable(const int *arr, const int size, int *table);
void printNum(const int *arr, const int loc, const int size);
int main(void) {
int n;
scanf("%d", &n);
int arr[n];
// Initialize array
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
if (arr[i] > maxnum)
maxnum = arr[i];
}
int hash[maxnum];
mkhashtable(arr, n, hash);
// Search
int m;
scanf("%d", &m);
int tmp;
for (int i = 0; i < m; i++) {
scanf("%d", &tmp);
if (tmp < 0 || tmp >= maxnum) { // Not in the hash table
printf("NULL\n");
} else {
printNum(arr, hash[tmp], n);
}
}
return 0;
}
void mkhashtable(const int *arr, const int size, int *table) {
// Initialize
for (int i = 0; i < maxnum; i++) {
table[i] = -1;
}
// Fill values
for (int i = 0; i < size; i++) {
table[arr[i]] = i;
}
return;
}
void printNum(const int *arr, const int loc, const int size) {
if (loc == -1) {
printf("NULL\n");
} else {
if (loc - 1 >= 0)
printf("%d ", arr[loc - 1]);
if (loc + 1 <= size)
printf("%d ", arr[loc + 1]);
printf("\n");
}
}