Skip to content

Instantly share code, notes, and snippets.

@iamgauravbisht
Created December 24, 2023 20:43
Show Gist options
  • Save iamgauravbisht/b01b292e535058c02f9a4a23623df48f to your computer and use it in GitHub Desktop.
Save iamgauravbisht/b01b292e535058c02f9a4a23623df48f to your computer and use it in GitHub Desktop.
Logarithmic Space Time Complexity
package spaceTimeComplexity;
public class Logarithmic {
public static void main(String[] args) {
//Binary Search
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target = 6;
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = (left + right ) / 2;
// Check if the target is present at the mid
if (arr[mid] == target) {
System.out.println(target + " found at Index : " + mid);
break;
}
// If target is greater, ignore the left half
if (arr[mid] < target) {
left = mid + 1;
System.out.println("left");
}
// If target is smaller, ignore the right half
else {
right = mid - 1;
System.out.println("right");
}
}
}
}
// output
// left
// right
// 6 found at Index : 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment