diff --git a/README.md b/README.md index 306eb5f3..0a652f29 100644 --- a/README.md +++ b/README.md @@ -425,8 +425,8 @@ In order to achieve greater coverage and encourage more people to contribute to </a> </td> <td> <!-- Java --> - <a href="./CONTRIBUTING.md"> - <img align="center" height="25" src="./logos/github.svg" /> + <a href="./src/java/SentinelLinearSearch.java"> + <img align="center" height="25" src="./logos/java.svg" /> </a> </td> <td> <!-- Python --> diff --git a/src/java/SentinelLinearSearch.java b/src/java/SentinelLinearSearch.java new file mode 100644 index 00000000..6eba6bba --- /dev/null +++ b/src/java/SentinelLinearSearch.java @@ -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; + } +} \ No newline at end of file