Revise later
SpaceTo flip
If confident
All Flashcards
What are the steps of Linear Search?
- Start at the first element. 2. Compare the current element with the target. 3. If they match, return the index. 4. If not, move to the next element. 5. Repeat steps 2-4 until the target is found or the end of the list is reached. 6. If the end is reached without finding the target, return -1.
What are the differences between Linear Search and Binary Search?
Linear Search: Works on unsorted data, O(n) time complexity. | Binary Search: Requires sorted data, O(log n) time complexity.
What does the following code output?
java
ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(2, 4, 6, 8, 10));
int target = 6;
System.out.println(linearSearch(arr, target));
2
What does the following code output?
java
int[] arr = {1, 3, 5, 7, 9};
int target = 2;
System.out.println(linearSearch(arr, target));
-1
Identify the error in the following code:
java
public static int linearSearch(ArrayList<String> array, int n) {
for (int i = 0; i < array.size(); i++) {
if (array.get(i) == n) {
return i;
}
}
return -1;
}
The method expects an ArrayList of Strings but compares the elements to an integer n. The parameter type should be String n.
Complete the following code snippet for linear search in an integer array:
java
public static int linearSearch(int[] array, int n) {
for (int i = 0; i < array.length; i++) {
if (array[i] == n) {
// Complete this line
}
}
return -1;
}
return i;
What does the following code output?
java
ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(5, 10, 15, 20));
int target = 5;
System.out.println(linearSearch(arr, target));
0
What does the following code output?
java
int[] arr = {5, 10, 15, 20};
int target = 25;
System.out.println(linearSearch(arr, target));
-1