Repository navigation
Expand file tree
/
Copy pathSearching.java
More file actions
60 lines (54 loc) · 2.06 KB
/
Copy pathSearching.java
File metadata and controls
60 lines (54 loc) · 2.06 KB
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
package com.example.sortingAndSearching;
public class Searching {
/**
* Searches the specified array of objects using a linear search algorithm.
*
* @param <T> parameterized type
* @param data the array to be sorted
* @param target the element being searched for
* @return true if the desired element is found
*/
public static <T extends Comparable<? super T>> boolean linearSearch(T[] data, T target) {
for (T item : data) {
if (item.compareTo(target) == 0)
return true;
}
return false;
}
/**
* Searches the specified array of objects using a binary search algorithm.
*
* @param <T> parameterized type
* @param data the array to be sorted
* @param target the element being searched for
* @return true if the desired element is found
*/
public static <T extends Comparable<? super T>> boolean binarySearch(T[] data, T target) {
return binarySearch(data, 0, data.length - 1, target);
}
/**
* Searches the specified array of objects using a binary search algorithm.
*
* @param <T> parameterized type
* @param data the array to be sorted
* @param startIndex the start index of the array
* @param endIndex the end index of the array
* @param target the element being searched for
* @return true if the desired element is found
*/
public static <T extends Comparable<? super T>> boolean binarySearch(T[] data, int startIndex, int endIndex, T target) {
boolean found = false;
int midpoint = (startIndex + endIndex) / 2;
int compare = target.compareTo(data[midpoint]);
if (compare == 0) {
found = true;
} else if (compare < 0) {
if (startIndex <= midpoint - 1) {
found = binarySearch(data, startIndex, midpoint - 1, target);
}
} else if (midpoint + 1 <= endIndex) {
found = binarySearch(data, midpoint + 1, endIndex, target);
}
return found;
}
}