|
18 | 18 | */ |
19 | 19 | public class LinearSearch implements SearchAlgorithm { |
20 | 20 |
|
21 | | - /** |
22 | | - * Generic Linear search method |
| 21 | + /** |
| 22 | + * Generic Linear search method. |
23 | 23 | * |
24 | | - * @param array List to be searched |
| 24 | + * <p> |
| 25 | + * This method takes an array of elements and a key to search for. |
| 26 | + * It traverses the array and compares each element with the key using |
| 27 | + * the {@code compareTo()} method. If a match is found, it returns |
| 28 | + * the index of the element; otherwise, it returns {@code -1}. |
| 29 | + * |
| 30 | + * <p> |
| 31 | + * The linear search algorithm can work on both sorted and unsorted data. |
| 32 | + * However, it has a time complexity of O(n) in the worst and average cases, |
| 33 | + * as it may need to check every element. |
| 34 | + * |
| 35 | + * <p> |
| 36 | + * <b>Note on {@link Comparable}:</b> <br> |
| 37 | + * The type parameter {@code <T extends Comparable<T>>} ensures that the elements of |
| 38 | + * the array implement the {@link Comparable} interface. This means each element knows |
| 39 | + * how to compare itself with another element of the same type using the |
| 40 | + * {@code compareTo()} method. |
| 41 | + * |
| 42 | + * <p> |
| 43 | + * Example usage: |
| 44 | + * <pre>{@code |
| 45 | + * if (array[i].compareTo(value) == 0) { |
| 46 | + * return i; |
| 47 | + * } |
| 48 | + * }</pre> |
| 49 | + * The {@code compareTo()} method returns {@code 0} if both elements are equal. |
| 50 | + * Using {@code Comparable} allows this algorithm to work with any object type |
| 51 | + * (such as Integer, String, or custom classes) that defines its own comparison logic. |
| 52 | + * |
| 53 | + * @param array Array to be searched |
25 | 54 | * @param value Key being searched for |
26 | | - * @return Location of the key |
| 55 | + * @param <T> The type of elements in the array, which must implement Comparable |
| 56 | + * @return Index of the key if found, otherwise -1 |
27 | 57 | */ |
28 | 58 | @Override |
29 | 59 | public <T extends Comparable<T>> int find(T[] array, T value) { |
|
0 commit comments