Skip to content

Commit 68380d0

Browse files
authored
Docs: Explain use of Comparable in LinearSearch for better clarity
Updated the documentation for the generic Linear Search method by adding a detailed explanation of the Comparable interface. This helps new or unfamiliar programmers better understand the purpose of generics and how compareTo() is used in comparisons.
1 parent 4858ec9 commit 68380d0

File tree

1 file changed

+34
-4
lines changed

1 file changed

+34
-4
lines changed

src/main/java/com/thealgorithms/searches/LinearSearch.java

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,42 @@
1818
*/
1919
public class LinearSearch implements SearchAlgorithm {
2020

21-
/**
22-
* Generic Linear search method
21+
/**
22+
* Generic Linear search method.
2323
*
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
2554
* @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
2757
*/
2858
@Override
2959
public <T extends Comparable<T>> int find(T[] array, T value) {

0 commit comments

Comments
 (0)