Search Algorithms and Complexity Analysis
Search Algorithms and Complexity Analysis
Linear search is preferred when the list is unsorted, as binary search requires a sorted list to operate correctly . In situations where the overhead of sorting a list for a single search is too high, or where the list frequently changes, linear search becomes more practical.
When performing a sequential search for a non-existent key like 13 in the ordered list [3, 5, 6, 8, 11, 12, 14, 15, 17, 18], 7 comparisons are needed . The search must check each element until the list ends or a match is found.
Big O notation is useful because it provides a way to describe the upper bound performance or worst-case scenario of an algorithm's efficiency in terms of time (or space), allowing for a comparative analysis of algorithm efficiency independent of machine or runtime conditions .
Using a method with poorer worst-case complexity might be appropriate when specific constraints, like memory limitations or dynamic data input reducing overhead through less complexity in setup (like sorting), make it more efficient in practice than theoretically optimal algorithms .
To find the first occurrence of the key 18, two comparisons are necessary, as 18 is found as the second element in the list .
In the worst case, binary search would require examining no more than 8 names . This is approximately log2(193), which rounds up to 8.
Binary search requires fewer comparisons because it eliminates half of the remaining elements in each step by leveraging the sorted nature of the dataset, effectively reducing the problem size logarithmically (O(log N)), unlike linear search which checks each element one by one (O(N)).
The sequence of comparisons for searching the key 16 is 12, 17, 15 . The search proceeds by selecting the middle element 12, then 17, and finally checking 15.
The sequence of comparisons made is 12, 6, 11, 8 . The initial midpoint is 12, leading to a search on the left side with midpoint 6, then 11, and finally narrowing down to the correct key 8.
The big O notations are as follows: For 4N^2 + 2N + 2, the dominant term is N^2, so the time complexity is O(N^2). For N + log N, N is the dominant term, so the time complexity is O(N). For N log N, the time complexity is directly O(N log N). For a constant, such as 3, the time complexity is O(1).