3434 * @see SearchAlgorithm
3535 */
3636public class SentinelLinearSearch implements SearchAlgorithm {
37-
3837 /**
3938 * Performs sentinel linear search on the given array.
4039 *
4140 * @param array the array to search in
42- * @param key the element to search for
43- * @param <T> the type of elements in the array, must be Comparable
41+ * @param key the element to search for
42+ * @param <T> the type of elements in the array, must be Comparable
4443 * @return the index of the first occurrence of the key, or -1 if not found
4544 * @throws IllegalArgumentException if the array is null
4645 */
@@ -49,44 +48,44 @@ public <T extends Comparable<T>> int find(T[] array, T key) {
4948 if (array == null ) {
5049 throw new IllegalArgumentException ("Array cannot be null" );
5150 }
52-
51+
5352 if (array .length == 0 ) {
5453 return -1 ;
5554 }
56-
55+
5756 if (key == null ) {
5857 return findNull (array );
5958 }
60-
59+
6160 // Store the last element
6261 T lastElement = array [array .length - 1 ];
63-
62+
6463 // Place the sentinel (search key) at the end
6564 array [array .length - 1 ] = key ;
66-
65+
6766 int i = 0 ;
6867 // Search without bound checking since sentinel guarantees we'll find the key
6968 while (array [i ].compareTo (key ) != 0 ) {
7069 i ++;
7170 }
72-
71+
7372 // Restore the original last element
7473 array [array .length - 1 ] = lastElement ;
75-
74+
7675 // Check if we found the key before the sentinel position
7776 // or if the original last element was the key we were looking for
7877 if (i < array .length - 1 || (lastElement != null && lastElement .compareTo (key ) == 0 )) {
7978 return i ;
8079 }
81-
80+
8281 return -1 ; // Key not found
8382 }
84-
83+
8584 /**
8685 * Helper method to find null values in the array.
8786 *
8887 * @param array the array to search in
89- * @param <T> the type of elements in the array
88+ * @param <T> the type of elements in the array
9089 * @return the index of the first null element, or -1 if not found
9190 */
9291 private <T extends Comparable <T >> int findNull (T [] array ) {
@@ -97,4 +96,4 @@ private <T extends Comparable<T>> int findNull(T[] array) {
9796 }
9897 return -1 ;
9998 }
100- }
99+ }
0 commit comments