Searching an unsorted array involves locating a specific element or determining whether it exists within the array. Since the elements are not organized in any specific order, the most common method of searching is through linear search.
Here’s a step-by-step outline of how linear search works:
Here’s a simple C++ implementation of linear search for an unsorted array:
#include <iostream>
using namespace std;
// Function to perform linear search
int linearSearch(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Return the index if found
}
}
return -1; // Return -1 if the target is not found
}
int main() {
int arr[] = {3, 5, 2, 9, 1, 7}; // Example unsorted array
int size = sizeof(arr) / sizeof(arr[0]);
int target = 9;
int result = linearSearch(arr, size, target);
if (result != -1) {
cout << "Element found at index: " << result << endl; // Output: Element found at index: 3
} else {
cout << "Element not found." << endl; // Output if not found
}
return 0;
}
linearSearch function takes an array, its size, and the target value as parameters.linearSearch function. The result is then printed.Searching an unsorted array using linear search is efficient for small arrays or when a simple implementation is needed. However, for larger datasets, other search algorithms (like binary search) require sorted arrays and can be significantly faster, operating in time. When dealing with unsorted data, linear search remains a fundamental method due to its simplicity and directness.
Open this section to load past papers