Linear Search with Enhanced Features
You can enhance the basic linear search implementation by adding features such as counting occurrences, returning multiple indices, or handling different data types.
PHP
<?php function linearSearch( $arr , $target , $occurrences = false) { $length = count ( $arr ); $indices = []; for ( $i = 0; $i < $length ; $i ++) { if ( $arr [ $i ] == $target ) { $indices [] = $i ; if (! $countOccurrences ) { return $indices ; } } } return $occurrences ? count ( $indices ) : $indices ; } // Driver code $arr = [10, 20, 30, 40, 50]; $targetValue = 30; $result = linearSearch( $arr , $targetValue ); if ( is_array ( $result )) { echo "Element found at index " . implode( ', ' , $result ); } else { echo "Element not found in the array" ; } ?> |
Output
Element found at index 2
Implementation of Linear Search in PHP
Linear search, also known as sequential search, is a basic method for finding a specific element in an array. In this article, we will explore the implementation of linear search in PHP.