-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP113_Q1.cpp
More file actions
53 lines (46 loc) · 797 Bytes
/
P113_Q1.cpp
File metadata and controls
53 lines (46 loc) · 797 Bytes
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
48
49
50
51
52
53
#include <stdio.h>
#include <stdlib.h>
#pragma warning(disable:4996)
/* --- 요소의 개수가 n인 배열 a에서 key와 일치하는 요소를 선형 검색(보초법) --- */
int search(int a[], int n, int key)
{
int i = 0;
a[n] = key;
/*
while (1)
{
if (a[i] == key)
break;
++i;
}
*/
for (i = 0; i < n; ++i)
{
if (a[i] == key)
break;
}
return i == n ? -1 : i;
}
int main()
{
int i, nx, ky, idx;
int* x;
puts("선형 검색(보초법)");
printf("요소 개수 : ");
scanf("%d", &nx);
x = (int*)calloc(nx + 1, sizeof(int));
for (i = 0; i < nx; ++i)
{
printf("x[%d] : ", i);
scanf("%d", &x[i]);
}
printf("검색값: ");
scanf("%d", &ky);
idx = search(x, nx, ky);
if (idx == -1)
puts("검색에 실패했습니다.");
else
printf("%d(은)는 x[%d]에 있습니다.\n", ky, idx);
free(x);
return 0;
}