-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSequentialSearch.c
More file actions
82 lines (71 loc) · 1.91 KB
/
SequentialSearch.c
File metadata and controls
82 lines (71 loc) · 1.91 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define _CRT_SECURE_NO_WARNNING
#define SIZE 10
struct Node {
int key;
struct Node* link;
};
void insert(struct Node* head, int key) {
struct Node* pos = head;
struct Node* pre;
while (pos != NULL) {
pre = pos;
pos = pre->link;
}
struct Node* newNode = (struct Node*)malloc(sizeof(*newNode));
newNode->key = key;
pre->link = newNode;
newNode->link = NULL;
}
/**
* 배열 순차 탐색
* @param a 배열
* @param key 찾을 키
* return 찾은 키의 인덱스. 못 찾으면 0 반환
*/
int arrSeqSearch(int a[], int key){
int i = 0;
while ((i < SIZE) && a[i] != key) i++;
return i;
}
/**
* 연결 리스트 순차 탐색
* @param head 연결 리스트의 첫 노드
* @param key 찾을 키
* return 찾은 키를 갖는 노드의 포인터. 없으면 NULL 반환(끝까지 가니까)
*/
struct Node* llSeqSearch(struct Node* head, int key) {
struct Node* pos = head->link;
while ((pos != NULL) && (pos->key != key)) pos = pos->link;
return pos;
}
int main() {
int a[SIZE];
struct Node* head = (struct Node*)malloc(sizeof(*head));
head->key = 0;
head->link = NULL;
srand(time(0));
for (int i = 0; i < SIZE; i++) {
int num = rand() % 10 + 1;
a[i] = num;
insert(head, num);
}
printf("random number in array: ");
for (int i = 0; i < SIZE; i++) {
printf("%d%c", a[i], (i == SIZE-1)?'\n':' ');
}
printf("random number in linked list: ");
struct Node* pos = head->link;
while (pos != NULL) {
printf("%d ", pos->key);
pos = pos->link;
}
printf("\n");
int num;
printf("input number for search: ");
scanf("%d", &num);
printf("sequential search used by array: %d\n", arrSeqSearch(a, num));
printf("sequential Search used by linked list: %d\n", llSeqSearch(head, num)->key);
}