There are two points , and data points in a 2-dimensional Euclidean plane. Assume that the distance between and , and the distances between and the data points are given. The distances between and the data points are not given, but a function defined below can be used to identify the sign of for .
Assume that for any .
(1) Show the pseudo-code of an algorithm to sort by ascending order of the distances from in worst computational time.
(2) Explain why the worst computational time of the algorithm shown in (1) is .
(3) Prove that if then .
(4) When are already sorted by ascending order of the distances from , show an algorithm to sort by ascending order of the distances from that calls function the minimum number of times, and evaluate that number of times.
P.S.: Quicksort can also be used to sort the points by distances from in worst computational time.
(2) Explain the worst computational time of the algorithm shown in (1) is
The merge sort algorithm has a time complexity of , where is the number of elements to sort because it divides the array into two halves and recursively sorts them in a time complexity of in each step. In this case, , so the time complexity of the merge sort algorithm is .
(4) Algorithm to sort by ascending order of the distances from
Given that for any , we can find out that for any (), since . This implies that by the proof in (3).
Therefore, we can sort by combining two sorted arrays and , where and are sorted by and , respectively.
So we can use the following algorithm to merge two sorted arrays and :
defsort_by_distances_from_B(points, distances_from_A, distances_from_B): # 2^n points sorted by distances from A sorted_points =[] i, j =0,0# Pointers for the two sorted arrays # Merge the two sorted arrays of n/2 points each while i <len(points)and j <len(points): if f(points[i], points[j])==1:# b_i > b_j sorted_points.append(points[i]) i +=1 else: sorted_points.append(points[j]) j +=1 return sorted_points
Evaluation of the number of times the function is called
The function is called times in the worst case. This is because the function is called for each pair of points in the two sorted arrays of points each. The function is called times to compare the distances between the points in the two arrays.