Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e13a6ea

Browse files
binary search algo
1 parent 99b42cb commit e13a6ea

File tree

1 file changed

+21
-25
lines changed

1 file changed

+21
-25
lines changed

‎Searching/binarySearch.java

Lines changed: 21 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,34 +2,30 @@
22
class binarySearch {
33

44
public static void main(String[] args) {
5-
int arr[] = {1, 2, 3, 4, 5, 6, 57, };
6-
int target = 6;
7-
int result = binarySearching(arr, target);
8-
System.out.println("the target element index is: " + result);
9-
10-
}
11-
12-
public static int binarySearching(int arr[], int target) {
5+
int[] arr = {3, 5, 7, 9, 11, 13, 15, 17};
6+
int target_item = 13;
7+
int result = binarySearching(arr, target_item);
138

14-
int start = 0;
15-
int end = arr.length - 1;
16-
int mid;
9+
if (result != -1) {
10+
System.out.println("element in index of : " + result);
11+
} else {
12+
System.out.println("element not found..");
13+
}
14+
}
1715

18-
while (start <= end) {
19-
mid = (start + end) / 2;
20-
if (arr[mid] == target) {
16+
public static int binarySearching(int[] a, int target) {
17+
int left = 0;
18+
int right = a.length - 1;
19+
while (left <= right) {
20+
int mid = (left + right) / 2;
21+
if (a[mid] == target) {
2122
return mid;
22-
} else {
23-
if(target < arr[mid]){
24-
end = mid - 1;
25-
}else{
26-
start = mid + 1;
27-
}
28-
}
29-
23+
} else if (a[mid] < target) {
24+
left = mid + 1;
25+
}else{
26+
right = mid - 1;
3027
}
31-
32-
return -1;
3328
}
29+
return -1;
3430
}
35-
31+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /