Skip to content

Commit cb9c5b1

Browse files
committed
Add SentinelLinearSearch.java
1 parent 7d29522 commit cb9c5b1

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

src/java/SentinelLinearSearch.java

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
public class SentinelLinearSearch {
2+
public static void main(String[] args){
3+
int[] arr = {10,20,50,60,30,60,70,80,22,56,2,7,9,0,44};
4+
System.out.println(LinearSentinel(arr,70));
5+
System.out.println(LinearSentinel(arr,45));
6+
}
7+
8+
public static int LinearSentinel(int[] arr, int key){
9+
10+
int n = arr.length;
11+
12+
// Storing last element.
13+
int last = arr[n-1];
14+
15+
// Adding key at end index + 1
16+
arr[n-1] = key;
17+
18+
int i = 0;
19+
for(i = 0; i<n;i++){
20+
if(arr[i] == key) break;
21+
}
22+
23+
// Restoring the last element
24+
arr[n-1] = last;
25+
26+
// Returning index when found.
27+
if((i<n-1) || arr[n-1] == key){ return i;}
28+
29+
// Returning -1 if not found
30+
else return -1;
31+
}
32+
}

0 commit comments

Comments
 (0)