-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSearch.java
68 lines (41 loc) · 1.01 KB
/
Search.java
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.test.java;
import java.util.Arrays;
public class Search {
public int linearSearch(int[] arr, int number) {
for (int i=0; i<arr.length; i++) {
if (number == arr[i]) {
return i;
}
}
return -1;
}
public int binarySearch(int[] arr, int number) {
int front = 0;
int back = arr.length - 1;
while (front <= back) {
int mid = (front + back) / 2;
if (number > arr[mid]) {
front = mid + 1;
}
if (number < arr[mid]) {
back = mid - 1;
}
if (number == arr[mid]) {
System.out.println("Index : " + mid);
return mid;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = new int[] {2, 3, 4, 65, 21, 54, 452, 78, 98, 34};
Search search = new Search();
int index = search.linearSearch(arr, 34);
System.out.println("Index : " + index);
Arrays.sort(arr);
int i = search.binarySearch(arr, 78);
if (i == -1) {
System.out.println("Not found");
}
}
}