Divide and Conquer
更新日期:
Defintion of Divide and Conquer
Divide the problem into smaller problem, use the result of the small problems to form the result of the bigger problem.
Merge Sort
Divide the elements into two parts, recursively divide each parts until two elements are remained, merge each part together.
Each level operation is n
Total running time = each level big O number of level
Number of level = 2 log2 n
= n 2 log2 n
= n log2 n
Running time: O(n log n)
Sample code written in C
1 | #include <stdio.h> |
Counting inversion
Counting inversion is one of the application of merge sort.
In the “merge process”, it can be used to “count the inversion”.
if (array contains only one element) return 0 Divide array into A & B a = Sort-and-Count(A) b = Sort-and-Count(B) c = Merge-and-Count(A, B) return a + b + c;
Cloest Pair
It can be done by dividing the panel into left and right panel and finding the closest pair recursively in each part.
To find the closes pair perhaps connecting from left panel to right panel
we need to test 2 * beta distance
which beta is defined as min(closest_distance(left), closest_distance(right))
[Left][Right]
[Left<-beta->][<-beta->Right]
People find that in order to find the closest pair of an particular point in beta area, they just need to test its 11-th consecutive point in y coordinate
let yg be the elements in the beta element
for (int i = 0; i < yg.length; i++)
for (int j = 1; j <= 11; j++)
if (distance(yg[i], yg[i+j] < beta)
beta = distance(yg[i], yg[i+j])