Trace a walkthrough of: Linear search for 7 in: -7, 1, 3, 3, 4, 7, 11, 13 Binary
ID: 3740975 • Letter: T
Question
Trace a walkthrough of:
Linear search for 7 in: -7, 1, 3, 3, 4, 7, 11, 13
Binary Search for 8 in: -7, 2, 2, 3, 4, 7, 8, 11, 13
Binary Search for 8 in: -7, 1, 2, 3, 5, 7, 10, 13
Modify the mergesort algorithm to remove duplicates in the merging step to obtain an algorithm that removes duplicates from an array. Note that the resulting array does not have the same ordering as the original one. What is the efficiency of this algorithm?
A stable sort does not change the order of elements with the same value. This is a desirable feature in many applications. Consider a sequence of e-mail messages. If you sort by date and then by sender, you’d like the second sort to preserve the relative order of the first, so you can see all messages from the same sender in date order. Is selection sort stable? Insertion sort? Why or why not?
Explanation / Answer
Here is the code for the first question:
Trace a walkthrough of:
Linear search for 7 in: -7, 1, 3, 3, 4, 7, 11, 13
Linear search algorithm is a brute force approach, and will just compare from first till
either the element is found, or till the list is exhausted.
So,
i = 0, -7 == 7: Fail.
i = 1, 1 == 7: Fail.
i = 2, 3 == 7: Fail.
i = 3, 3 == 7: Fail.
i = 4, 4 == 7: Fail.
i = 5, 7 == 7: Success.
So, the algorithm returns the index 5.
Binary Search for 8 in: -7, 2, 2, 3, 4, 7, 8, 11, 13
Binary search algorithm everytime calculates the mid value of the index, and will compare
the element with that index, and will remove one half of the list, based on the value, or
the indices crossover.
start = 0, end = 8, mid = 4. list[4] = 4. 8 > 4, so search in the right half.
start = 5, end = 8, mid = 6. list[6] = 8. 8 == 8, so the search comes to an end, and will return index 6.
Binary Search for 8 in: -7, 1, 2, 3, 5, 7, 10, 13
start = 0, end = 7, mid = 3. list[3] = 3. 8 > 3, so search in the right half.
start = 4, end = 7, mid = 5. list[5] = 7. 8 > 7, so search in the right half.
start = 6, end = 7, mid = 6. list[6] = 10. 8 < 10, so search in the left half.
start = 6, end = 5, indices crossed, so conclude the element is not in the list, and return -1.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.