-
Notifications
You must be signed in to change notification settings - Fork 0
/
Search.java
72 lines (55 loc) · 1.84 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
69
70
71
72
/*
* Basic implementation of the Simple (Stupid, Linear) Search and Binary Search algorithms
* along with a runtime comparison
*
* @author Marcin Danlowski
* https://github.com/mdanlowski/
*
*/
public class Search{
static class SearchMethods{
public static int linearSearch(int[] list, int item){
for ( int i=0; i<list.length; i++ ){
if(list[i] == item){
return i;
}
}
return -1;
}
public static int binarySearch(int[] list, int item){
int low = 0;
int hi = list.length-1;
while ( low <= hi ){
int pvt = (int) (low+hi)/2;
if( pvt == item ) return pvt;
if( pvt > item ) hi = pvt-1;
else low = pvt+1;
}
return -1;
}
}
public static void main(String[] args){
// GENERATE DATA
int[] data = new int[100000000];
for(int i=0; i<data.length; i++){
data[i] = i;
}
int item = (int) Math.round( 100000000 * Math.random() );
long start = System.currentTimeMillis();
System.out.println(SearchMethods.linearSearch(data, 100000000-1/*item*/));
long stop = System.currentTimeMillis() - start;
System.out.println("LS DONE. Worst case: " + stop + "ms");
start = System.currentTimeMillis();
System.out.println(SearchMethods.linearSearch(data, item));
stop = System.currentTimeMillis() - start;
System.out.println("LS DONE. Random case: " + stop + "ms");
start = System.currentTimeMillis();
System.out.println(SearchMethods.binarySearch(data, item));
stop = System.currentTimeMillis() - start;
System.out.println("BS DONE. Random case: " + stop + "ms");
start = System.currentTimeMillis();
System.out.println(SearchMethods.binarySearch(data, item));
stop = System.currentTimeMillis() - start;
System.out.println("BS DONE. Random case: " + stop + "ms");
}
}