Skip to content

Commit d716035

Browse files
authored
Merge pull request #355 from varnan6/main
Add SentinelLinearSearch.java and Update README.md
2 parents a9fe3b0 + 909943a commit d716035

2 files changed

Lines changed: 34 additions & 2 deletions

File tree

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1527,8 +1527,8 @@ In order to achieve greater coverage and encourage more people to contribute to
15271527
</a>
15281528
</td>
15291529
<td> <!-- Java -->
1530-
<a href="./CONTRIBUTING.md">
1531-
<img align="center" height="25" src="./logos/github.svg" />
1530+
<a href="./src/java/SentinelLinearSearch.java">
1531+
<img align="center" height="25" src="./logos/java.svg" />
15321532
</a>
15331533
</td>
15341534
<td> <!-- Python -->

src/java/SentinelLinearSearch.java

Lines changed: 32 additions & 0 deletions
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)