分治法的思想像是分开求解然后和并,原问题从而得到解决。分治法的思想在算法设计中广泛使用,例如归并排序、快速排序、二分查找等等。
将查找区间分为两个区间,通过判断中间值可以得出原问题的答案位于哪个区间,在这个区间再次利用这种方法,最终找出答案。
用到了分治法解题步骤中的1、2
#include
#include
#include
using namespace std;
class BinarySearch{
public:
static int binarySearch(int* a, int first ,int last,int key){
assert(a != 0);
if (first <= last){
int mid = first + ((last - first) >> 1);
if (a[mid] == key){
return mid;
}else if (a[mid] > key){
binarySearch(a, first, mid - 1, key);
}
else{
binarySearch(a, mid + 1, last, key);
}
}
else{
return -1;
}
}
};
int main(){
int a[] = { 1, 4, 9, 17, 24, 29, 32 };
cout << BinarySearch::binarySearch(a, 0, sizeof(a) / sizeof(int), 9) << endl
<< BinarySearch::binarySearch(a,0,sizeof(a)/sizeof(int),10)<return 0;
}
class MergeSort{
public:
static void merge(int* a, int first,int last){
int* temp = new int[last - first];
merge(a, temp, first, last-1);
delete[] temp;
}
private:
static void merge(int* a, int* d, int l, int h){
if (l < h){
int mid = l + ((h - l) >> 1);
merge(a, d, l, mid);
merge(a, d, mid + 1, h);
And(a, d, l, mid + 1, h);//和并
}
//else不需要求解
}
//两个有序序列的和并
static void And(int* a, int* d, int l1, int l2, int h2){
int h1 = l2 - 1;
int i = l1;
int j = l1;
while (l1 <= h1 && l2 <= h2){
if (a[l1] <= a[l2]){
d[i++] = a[l1++];
}
else{
d[i++] = a[l2++];
}
}
while (l1 <= h1){
d[i++] = a[l1++];
}
while (j < i){
a[j] = d[j];
++j;
}
}
};
class ReverseOrderPair{
public:
static int merge(int* a, int first, int last){
int* temp = new int[last - first];
int count = merge(a, temp, first, last-1);
delete[] temp;
return count;
}
private:
static int AndCount(int* a, int* d, int l1, int l2, int h2){
int h1 = l2 - 1;
int i = l1;
int j = l1;
int count = 0;
while (l1 <= h1 && l2 <= h2){
if (a[l1] <= a[l2]){
d[i++] = a[l1++];
}
else{
d[i++] = a[l2++];
count += h1 - l1 + 1;//l1当前区间内可以与a[l2]构成逆序对的个数
}
}
while (l1 <= h1){
d[i++] = a[l1++];
}
while (j < i){
a[j] = d[j];
++j;
}
return count;
}
static int merge(int* a, int* d, int l, int h){
if (l < h){
int mid = l + ((h - l) >> 1);
int c1 = merge(a, d, l, mid);
int c2 = merge(a, d, mid + 1, h);
int c3 = AndCount(a, d, l, mid + 1, h);
return c1 + c2 + c3;
}
else{
return 0;
}
}
};