All Flashcards
What is the definition of Linear Search?
A searching algorithm that sequentially checks each element in a list until the target element is found or the list is exhausted.
What is the definition of Sequential Search?
A searching algorithm that sequentially checks each element in a list until the target element is found or the list is exhausted.
What is the definition of an ArrayList?
A resizable array implementation of the List interface.
What is the definition of 'index' in the context of searching?
The position of an element within a list or array.
What does it mean to 'search' in the context of data structures?
To find a specific element within a data structure and potentially return its location.
What is the return value if an element is not found in Linear Search?
-1
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 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