17-2 Making binary search dynamic
Binary search of a sorted array takes logarithmic search time, but the time to insert a new element is linear in the size of the array. We can improve the time for insertion by keeping several sorted arrays.
Specifically, suppose that we wish to support and on a set of elements. Let , and let the binary representation of be . We have sorted arrays , where for , the length of array is . Each array is either full or empty, depending on whether or , respectively. The total number of elements held in all arrays is therefore . Although each individual array is sorted, elements in different arrays bear no particular relationship to each other.
a. Describe how to perform the operation for this data structure. Analyze its worst-case running time.
b. Describe how to perform the operation. Analyze its worst-case and amortized running times.
c. Discuss how to implement .
a. We linearly go through the lists and binary search each one since we don't know the relationship between one list an another. In the worst case, every list is actually used. Since list has length and it's sorted, we can search it in time. Since varies from to , the runtime of SEARCH is .
b. To insert, we put the new element into and update the lists accordingly. In the worst case, we must combine lists into list Am. Since merging two sorted lists can be done linearly in the total length of the lists, the time this takes is . In the worst case, this takes time since could equal .
We'll use the accounting method to analyse the amoritized cost. Assign a cost of to each insertion. Thus, each item carries credit to pay for its later merges as additional items are inserted. Since an individual item can only be merged into a larger list and there are only lists, the credit pays for all future costs the item might incur. Thus, the amortized cost is .
c. Find the smallest such that in the binary representation of . If the item to be deleted is not in list , remove it from its list and swap in an item from Am, arbitrarily. This can be done in time since we may need to search list to find the element to be deleted. Now simply break list into lists by index. Since the lists are already sorted, the runtime comes entirely from making the splits, which takes time. In the worst case, this is .