forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSentinel_Search.dart
81 lines (65 loc) · 1.53 KB
/
Sentinel_Search.dart
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
/*
Sentinel Search implementation in Dart
In this search, the last element of the array is replaced with the
element to be searched and then the linear search is performed on the array.
*/
import 'dart:io';
bool Sentinel_Search(List arr, int n, int val) {
// Storing the last element and replacing it with the value to be searched
int last_ele = arr[n - 1];
arr[n - 1] = val;
int i = 0;
// Iterating over the list until we find the value to be searched
while (arr[i] != val) {
i += 1;
}
// Replacing the last element of list
arr[n - 1] = last_ele;
if (i < (n - 1) || arr[n - 1] == val) {
return true;
}
return false;
}
main() {
var array = [];
var n, ele, key;
print('Enter the number of elements: ');
n = stdin.readLineSync();
n = int.parse(n);
for (int i = 1; i <= n; i++) {
print('Enter value for element $i: ');
ele = stdin.readLineSync();
ele = int.parse(ele);
array.add(ele);
}
print('Enter the element to be searched: ');
key = stdin.readLineSync();
key = int.parse(key);
bool status = Sentinel_Search(array, n, key);
if (status) {
print('Element is present in array');
} else {
print('Element is not present in array');
}
}
/*
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(1)
Enter the number of elements:
6
Enter value for element 1:
12
Enter value for element 2:
43
Enter value for element 3:
33
Enter value for element 4:
56
Enter value for element 5:
12
Enter value for element 6:
90
Enter the element to be searched:
43
Element is present in array
*/