Skip to content

Commit 71a6890

Browse files
Completed the testing and implementation of the binary search algorithm on a sorted list
1 parent 30428c8 commit 71a6890

2 files changed

Lines changed: 33 additions & 1 deletion

File tree

‎src/com/sketch/Main.java‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,15 @@
11
package com.sketch;
22

3+
import com.sketch.search.*;
4+
35
public class Main {
46
public static void main(String[] args){
5-
System.out.println("Hello World!");
7+
int[] sortedArray = { 1, 2, 3, 5, 7, 9, 11, 14, 17, 26, 18, 37, 42, 43, 44, 47, 48, 49, 78, 227, 5556, 8976 };
8+
int valueToFind = 5556;
9+
10+
int binarySearchIndex = BinarySearch.search(sortedArray, valueToFind);
11+
12+
System.out.println("Expected Value Index: 20");
13+
System.out.println("Actual Value Index: " + binarySearchIndex);
614
}
715
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.sketch.search;
2+
3+
public class BinarySearch {
4+
public static int search(int[] sortedNumbers, int numberToFind){
5+
int low = 0;
6+
int high = sortedNumbers.length - 1;
7+
8+
while (low <= high){
9+
int middlePosition = (low + high) / 2;
10+
int middleNumber = sortedNumbers[middlePosition];
11+
if(middleNumber == numberToFind){
12+
return middlePosition;
13+
}
14+
else if(middleNumber < numberToFind){
15+
low = middlePosition + 1;
16+
}
17+
else {
18+
high = middlePosition - 1;
19+
}
20+
}
21+
22+
return -1;
23+
}
24+
}

0 commit comments

Comments
 (0)