Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -420,13 +420,13 @@ In order to achieve greater coverage and encourage more people to contribute to
</a>
</td>
<td> <!-- C++ -->
<a href="./CONTRIBUTING.md">
<a href="./src/java/CONTRIBUTING.md">
<img align="center" height="25" src="./logos/github.svg" />
</a>
</td>
<td> <!-- Java -->
<a href="./CONTRIBUTING.md">
<img align="center" height="25" src="./logos/github.svg" />
<a href="./src/java/SentinelLinearSearch.java.md">
<img align="center" height="25" src="./logos/java.svg" />
</a>
</td>
<td> <!-- Python -->
Expand Down
32 changes: 32 additions & 0 deletions src/java/SentinelLinearSearch.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
public class SentinelLinearSearch {
public static void main(String[] args){
int[] arr = {10,20,50,60,30,60,70,80,22,56,2,7,9,0,44};
System.out.println(LinearSentinel(arr,70));
System.out.println(LinearSentinel(arr,45));
}

public static int LinearSentinel(int[] arr, int key){

int n = arr.length;

// Storing last element.
int last = arr[n-1];

// Adding key at end index + 1
arr[n-1] = key;

int i = 0;
for(i = 0; i<n;i++){
if(arr[i] == key) break;
}

// Restoring the last element
arr[n-1] = last;

// Returning index when found.
if((i<n-1) || arr[n-1] == key){ return i;}

// Returning -1 if not found
else return -1;
}
}
Loading