kristofer a révisé ce gist . Aller à la révision
1 file changed, 42 insertions
linearsearchjava.md(fichier créé)
| @@ -0,0 +1,42 @@ | |||
| 1 | + | ```java | |
| 2 | + | public class LinearSearch { | |
| 3 | + | // Method that performs linear search | |
| 4 | + | public static int linearSearch(int[] array, int target) { | |
| 5 | + | // Iterate through each element in the array | |
| 6 | + | for (int i = 0; i < array.length; i++) { | |
| 7 | + | // If current element matches target, return its index | |
| 8 | + | if (array[i] == target) { | |
| 9 | + | return i; | |
| 10 | + | } | |
| 11 | + | } | |
| 12 | + | // If target is not found, return -1 | |
| 13 | + | return -1; | |
| 14 | + | } | |
| 15 | + | ||
| 16 | + | // Main method to test the linear search | |
| 17 | + | public static void main(String[] args) { | |
| 18 | + | // Test array | |
| 19 | + | int[] numbers = {4, 2, 7, 1, 9, 5, 3, 8, 6}; | |
| 20 | + | ||
| 21 | + | // Test cases | |
| 22 | + | int target1 = 7; // exists in array | |
| 23 | + | int target2 = 10; // doesn't exist in array | |
| 24 | + | ||
| 25 | + | // Search for target1 | |
| 26 | + | int result1 = linearSearch(numbers, target1); | |
| 27 | + | if (result1 != -1) { | |
| 28 | + | System.out.println("Element " + target1 + " found at index " + result1); | |
| 29 | + | } else { | |
| 30 | + | System.out.println("Element " + target1 + " not found in array"); | |
| 31 | + | } | |
| 32 | + | ||
| 33 | + | // Search for target2 | |
| 34 | + | int result2 = linearSearch(numbers, target2); | |
| 35 | + | if (result2 != -1) { | |
| 36 | + | System.out.println("Element " + target2 + " found at index " + result2); | |
| 37 | + | } else { | |
| 38 | + | System.out.println("Element " + target2 + " not found in array"); | |
| 39 | + | } | |
| 40 | + | } | |
| 41 | + | } | |
| 42 | + | ``` | |
Plus récent
Plus ancien