-
-
Notifications
You must be signed in to change notification settings - Fork 265
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #385 from itsAftabAlam/main
added question and solution on floor of a number in sorted array
- Loading branch information
Showing
2 changed files
with
29 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
Find the floor of a number in a sorted array . |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
public class FloorOfANumber { | ||
|
||
public static void main(String[] args) { | ||
int[] arr = {9, 11, 19, 22,23,24}; | ||
int target = 20; | ||
int ans = floor(arr, target); | ||
System.out.println(ans); | ||
} | ||
|
||
static int floor(int[] arr, int target) { | ||
int start = 0; | ||
int end = arr.length - 1; | ||
|
||
while(start <= end) { | ||
// finding the middle element | ||
int mid = (start + end) / 2; | ||
if (target < arr[mid]) { | ||
end = mid - 1; | ||
} else if (target > arr[mid]) { | ||
start = mid + 1; | ||
} else { | ||
// ans is found | ||
return mid; | ||
} | ||
} | ||
return end; | ||
} | ||
} |