-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinearSplitSearch.c
More file actions
98 lines (84 loc) · 1.94 KB
/
LinearSplitSearch.c
File metadata and controls
98 lines (84 loc) · 1.94 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <stdio.h>
//For the array size input
int arraySize(){
int s;
printf("Input the array size: ");
scanf("%d", &s);
return s;
}
//For the array input
void arrayInput(int s, int x[]){
printf("Input the array: ");
for(int j = 0; j < s; j++){
scanf("%d", &x[j]);
}
}
//Takes input of a target number
int targetInput(){
int t = 0;
do{
printf("Input a target number: ");
scanf("%d", &t);
if(t%1 != 0){
printf("\nInvalid Input!\n");
}
}while(t%1 != 0);
return t;
}
//The Linear Split Search Helper function for recursion
int helper(int s, int a[], int l, int r, int t, int f){
if(l > r){
return -1;
}
else if (f == 1){
if(a[l] == t)
return l;
int ls = helper(s, a, l+1, r, t, 1);
if(ls != -1)
return ls;
else
return -1;
}
else if(f == -1){
if(a[r] == t)
return r;
int rs = helper(s, a, l, r-1, t, -1);
if(rs != -1)
return rs;
else
return -1;
}
}
//The Linear Split Search algorithm using recursion
int linearSearch(int s, int a[], int t){
int m = s/2;
int ls = helper(s, a, 0, m, t, 1);
if(ls != -1)
return ls;
int rs = helper(s, a, m+1, s-1, t, -1);
if(rs != -1)
return rs;
return -1;
}
//For printing the search results
void searchResults(int t, int ti){
if(ti == -1){
printf("\n%d not found in the array.\n", t);
}
else{
printf("\n%d found at %d.\n", t, ti);
}
}
int main()
{
//Taking input
int s = arraySize();
int a[s];
arrayInput(s, a);
int t = targetInput();
//Searching using Recursive Linear Split Search and storing the index of the first occurance
int ti = linearSearch(s, a, t);
//Printing the output
searchResults(t, ti);
return 0;
}