Skip to content

Commit cfe92c6

Browse files
LinearSearch and BinarySearch Added.
1 parent 1404137 commit cfe92c6

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

src/com/mehmetpekdemir/Main.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import com.mehmetpekdemir.list.doublylinkedlist.EmployeeDoublyLinkedList;
44
import com.mehmetpekdemir.list.singlylinkedlist.EmployeeLinkedList;
5+
import com.mehmetpekdemir.search.binarysearch.BinarySearch;
6+
import com.mehmetpekdemir.search.linearsearch.LinearSearch;
57
import com.mehmetpekdemir.shared.Employee;
68
import com.mehmetpekdemir.sort.BubbleSort;
79
import com.mehmetpekdemir.sort.CountingSort;
@@ -146,6 +148,15 @@ public static void main(String[] args) {
146148

147149
System.out.println(linkedStack.peek());
148150

151+
System.out.println("\n---------- Linear Search ----------");
152+
153+
final int[] linearSearchArray = { 20, 35, -15, 7, 55, 1, -22 };
154+
System.out.println(LinearSearch.search(linearSearchArray, -15));
155+
156+
System.out.println("\n---------- Binary Search ----------");
157+
158+
final int[] binarySearchArray = { -22, -15, 1, 7, 20, 35, 55 };
159+
System.out.println(BinarySearch.search(binarySearchArray, -15));
149160
}
150161

151162
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.mehmetpekdemir.search.binarysearch;
2+
3+
/**
4+
*
5+
* @author MEHMET PEKDEMIR
6+
* @since 1.0
7+
*/
8+
public class BinarySearch {
9+
10+
public static int search(int[] input, int value) {
11+
int start = 0;
12+
int end = input.length;
13+
14+
while (start < end) {
15+
int midpoint = (start + end) / 2;
16+
if (input[midpoint] == value) {
17+
return midpoint;
18+
} else if (input[midpoint] < value) {
19+
start = midpoint + 1;
20+
} else {
21+
end = midpoint;
22+
}
23+
}
24+
25+
return -1;
26+
}
27+
28+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.mehmetpekdemir.search.linearsearch;
2+
3+
/**
4+
*
5+
* @author MEHMET PEKDEMIR
6+
* @since 1.0
7+
*/
8+
public class LinearSearch {
9+
10+
public static int search(int[] input, int value) {
11+
12+
for (int i = 0; i < input.length; i++) {
13+
if (input[i] == value) {
14+
return i;
15+
}
16+
}
17+
18+
return -1;
19+
}
20+
}

0 commit comments

Comments
 (0)