Created
May 5, 2024 05:19
-
-
Save pablohdzvizcarra/66c3ecd092bcb7269d2f25bd4d164c4a to your computer and use it in GitHub Desktop.
Binary Search and other algorithms implementations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ChapterTwoExercises { | |
/* | |
* Binary search implementation, to know the steps necessary only double the | |
* elements and plus 1 | |
* Array 3 = 2 steps | |
* Array 7 = 3 steps | |
* array 15 = 4 steps | |
* array 31 = 5 steps | |
* array 63 = 6 steps | |
* array 127 = 7 steps | |
* array 254 = 8 steps | |
*/ | |
public int binarySearch(int[] array, int target) { | |
int lowerBound = 0; | |
int upperBound = array.length - 1; | |
while (lowerBound <= upperBound) { | |
int midPoint = (upperBound + lowerBound) / 2; | |
int valueAtMidpointPoint = array[midPoint]; | |
if (target == valueAtMidpointPoint) { | |
return midPoint; | |
} | |
if (target < valueAtMidpointPoint) { | |
upperBound = midPoint - 1; | |
} else { | |
lowerBound = midPoint + 1; | |
} | |
} | |
return -1; | |
} | |
public int binarySearchTwo(int[] array, int target) { | |
int left = 0; | |
int right = array.length - 1; | |
while (left <= right) { | |
int mid = left + (right - left) / 2; | |
if (array[mid] == target) { | |
return mid; | |
} | |
if (array[mid] < target) { | |
left = mid + 1; | |
} else { | |
right = mid - 1; | |
} | |
} | |
return -1; | |
} | |
/* | |
* Time complexity: O(N) | |
*/ | |
public int doubleSearch(int[] elements, int target) { | |
int leftPointer = 0; | |
int rightPointer = elements.length - 1; | |
while (leftPointer <= rightPointer) { | |
if (elements[leftPointer] == target) { | |
return leftPointer; | |
} | |
if (elements[rightPointer] == target) { | |
return rightPointer; | |
} | |
leftPointer++; | |
rightPointer--; | |
} | |
return -1; | |
} | |
/* | |
* Time complexity: O(N) | |
*/ | |
public String reverseString(String value) { | |
StringBuilder builder = new StringBuilder(); | |
for (int i = value.length() - 1; i >= 0; i--) { | |
char word = value.charAt(i); | |
builder.append(word); | |
} | |
return builder.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment