FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
java-basics/core-java/basics/BinarySearch.java at patch-1 · CodeForHunger/java-basics · GitHub
CodeForHunger
/
java-basics
Public
forked from
learning-zone/java-basics
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
java-basics
/
core-java
/
basics
/
BinarySearch.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
47 lines (39 loc) · 928 Bytes
Breadcrumbs
java-basics
/
core-java
/
basics
/
BinarySearch.java
Copy path
File metadata and controls
47 lines (39 loc) · 928 Bytes
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Java implementation of iterative Binary Search
import
java
.
io
.*;
class
BinarySearch
{
// Returns index of x if it is present in arr[].
int
binarySearch
(
int
arr
[],
int
x
)
{
int
l
=
0
,
r
=
arr
.
length
-
1
;
while
(
l
<=
r
) {
int
m
=
l
+ (
r
-
l
) /
2
;
// Check if x is present at mid
if
(
arr
[
m
] ==
x
)
return
m
;
// If x greater, ignore left half
if
(
arr
[
m
] <
x
)
l
=
m
+
1
;
// If x is smaller, ignore right half
else
r
=
m
-
1
;
}
// If we reach here, then element was
// not present
return
-
1
;
}
// Driver code
public
static
void
main
(
String
args
[])
{
BinarySearch
ob
=
new
BinarySearch
();
int
arr
[] = {
2
,
3
,
4
,
10
,
40
};
int
n
=
arr
.
length
;
int
x
=
10
;
int
result
=
ob
.
binarySearch
(
arr
,
x
);
if
(
result
== -
1
)
System
.
out
.
println
(
"Element is not present in array"
);
else
System
.
out
.
println
(
"Element is present at "
+
"index "
+
result
);
}
}
Back
|
FazBrowse Home
|
New Git URL