From 4fcad4fcbc31cc43b91789260228878f01a47676 Mon Sep 17 00:00:00 2001 From: CodingCookieRookie <38324769+CodingCookieRookie@users.noreply.github.com> Date: Tue, 19 May 2020 23:20:48 +0800 Subject: [PATCH 1/2] Handles all corner cases --- Searches/Perfect BinarySearch | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Searches/Perfect BinarySearch diff --git a/Searches/Perfect BinarySearch b/Searches/Perfect BinarySearch new file mode 100644 index 00000000..28cdcb5b --- /dev/null +++ b/Searches/Perfect BinarySearch @@ -0,0 +1,21 @@ + static int binarySearch(int[] arr, int target) { + int low = 0 ; + int high = arr.length - 1 ; + + while(low <= high) { + int mid =(low + high) / 2; + + if(arr[mid] == target) { + return mid; + } + else if(arr[mid] > target) { + high = mid - 1; + } + else { + low = mid + 1; + } + + } + return -1; + } + From 6818098a32c14b1c6f8d6bf08f58f6c22d30ecc5 Mon Sep 17 00:00:00 2001 From: CodingCookieRookie <38324769+CodingCookieRookie@users.noreply.github.com> Date: Tue, 19 May 2020 23:53:52 +0800 Subject: [PATCH 2/2] Update SelectionSort.java -Used compareTo -Used a local swap method --- Sorts/SelectionSort.java | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/Sorts/SelectionSort.java b/Sorts/SelectionSort.java index 9b5b0cbc..e6b7c883 100644 --- a/Sorts/SelectionSort.java +++ b/Sorts/SelectionSort.java @@ -8,6 +8,17 @@ package Sorts; public class SelectionSort implements SortAlgorithm { + /** + * This method swaps the two elements in the array + * @param arr, i, j The array for the swap and + the indexes of the to-swap elements + */ + public void swap(T[] arr, int i, int j) { + T temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + /** * This method implements the Generic Selection Sort * @@ -22,14 +33,14 @@ public class SelectionSort implements SortAlgorithm { int min = i; for (int j = i + 1; j < n; j++) { - if (SortUtils.less(arr[j], arr[min])) { + if (arr[min].compareTo(arr[j]) < 0) { min = j; } } // Swapping if index of min is changed if (min != i) { - SortUtils.swap(arr, i, min); + swap(arr, i, min); } }