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 f350a92

Browse files
binary search added.
1 parent e8c2087 commit f350a92

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

‎src/search/BinarySearch.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,57 @@
11
package search;
22

3+
/**Binary search works only for sorted list of items.*/
34
public class BinarySearch {
45

6+
static int search(double[] numbers, double value){
7+
boolean found = false;
8+
int round = 0;
9+
int start = 0;
10+
int end = numbers.length - 1;
11+
int middle = 0;
12+
13+
while(!found){
14+
middle = (end + start) / 2;
15+
showStep(numbers, start, end, middle, round);
16+
17+
if(numbers[middle] == value)
18+
found = true;
19+
else if(numbers[middle] < value)
20+
start = middle + 1;
21+
else if(numbers[middle] > value)
22+
end = middle - 1;
23+
24+
round++;
25+
}
26+
27+
return middle;
28+
}
29+
static void showStep(double[] numbers, int start, int end, int mid, int round) {
30+
if(round == 0)
31+
System.out.println("BINARY SEARCH ALGORITHM");
32+
else
33+
System.out.println("round" + round + "=> search interval=[" + start + ", " + end+"] midInd= "+ mid +" value = " + numbers[mid]);
34+
System.out.println("------------------------------------------------------------------------------------------------------------------");
35+
}
36+
37+
public static void main(String[] args) {
38+
39+
double numbers[] = {-11, 0, 6, 10, 14, 20, 50, 73, 92, 100, 255};
40+
41+
/**print the sorted array*/
42+
System.out.print("Sorted List:{ ");
43+
for (int i = 0; i < numbers.length - 1; i++)
44+
System.out.print(numbers[i] + " ");
45+
System.out.println(numbers[numbers.length - 1]+" }");
46+
/**print subscripts*/
47+
System.out.print("indexes: ");
48+
for (int i = 0; i < numbers.length - 1; i++)
49+
System.out.print(i + " ");
50+
System.out.println(numbers.length - 1);
51+
52+
/**Execute the search algorithm*/
53+
search(numbers, 0);
54+
55+
}
56+
557
}

0 commit comments

Comments
(0)

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