From 106960e8212c90e107be1e311ced8df6bdd7a98f Mon Sep 17 00:00:00 2001 From: Jack Date: Sun, 6 Oct 2024 13:47:26 +0100 Subject: [PATCH 1/2] feat: added java binary search snippet --- Java/BinarySearch.java | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Java/BinarySearch.java diff --git a/Java/BinarySearch.java b/Java/BinarySearch.java new file mode 100644 index 0000000..219dc13 --- /dev/null +++ b/Java/BinarySearch.java @@ -0,0 +1,36 @@ +package java; + +public class BinarySearch {git + + // Pass in the array, the value to search for, + // the index of the start of the array, and the index of the end of the array + // The passing of index values will allow the same array to be utilised throughout each + // recursion, "filtering" out values that have been checked against by only looking between the indices + public static int binarySearch(int[] arr, int searchFor, int startIndex, int endIndex) { + // Binary search: (Assumes array is sorted) Splits the array in half using the midpoint, + // halving the data to look at each time by ignoring values that are less than or larger than + // the value being searched for. + // Time Complexity: Best - O(1) Average - O(log(n)) Worst - O(log(n)) + + // Check that there is more than one value in the array (low != high) + if (endIndex >= startIndex) { + int mid = startIndex + (endIndex - startIndex) / 2; + + // Check if searchFor is in the middle, if it is then return the index + if (arr[mid] == searchFor) { + return mid; + } + + // Check if the value is less than that at the mid, if it is, only look at the values to the left + // If not, the value is either to the right or not present so look at the right half instead + if (arr[mid] > searchFor) { + return binarySearch(arr, searchFor, startIndex, mid - 1); + } else { + return binarySearch(arr, searchFor, mid + 1, endIndex); + } + } + + // If the value is not found, return -1 + return -1; + } +} \ No newline at end of file From 6143dc8d121ff05eb1a8749dc0b27c9402476e58 Mon Sep 17 00:00:00 2001 From: Jack Date: Sun, 6 Oct 2024 13:54:23 +0100 Subject: [PATCH 2/2] fix: remove erroneous typo from class file --- Java/BinarySearch.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Java/BinarySearch.java b/Java/BinarySearch.java index 219dc13..f4e2d5a 100644 --- a/Java/BinarySearch.java +++ b/Java/BinarySearch.java @@ -1,6 +1,6 @@ package java; -public class BinarySearch {git +public class BinarySearch { // Pass in the array, the value to search for, // the index of the start of the array, and the index of the end of the array