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

52 lines
943 B
C

#include <stdio.h>
#include <stdlib.h>
int search(const int *arr, const int size, const int query);
int main(void) {
int n;
scanf("%d", &n);
int *arr = malloc(sizeof(int) * n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int m;
int tmp;
int loc;
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf("%d", &tmp);
loc = search(arr, n, tmp);
if (loc == -1) {
printf("NULL\n");
} else {
if (loc - 1 >= 0) {
if (loc + 1 < n) {
printf("%d %d\n", arr[loc - 1], arr[loc + 1]);
} else {
printf("%d\n", arr[loc - 1]);
}
} else {
if (loc + 1 < n) {
printf("%d\n", arr[loc + 1]);
} else {
printf("NULL\n");
}
}
}
}
free(arr);
return 0;
}
int search(const int *arr, const int size, const int query) {
for (int i = 0; i < size; i++) {
if (arr[i] == query) {
return i;
}
}
return -1;
}