这个想法是使用多个数组,每个数组长度为 2^k,根据 n 的二进制表示来存储 n 个元素。每个数组都是排序的,不同的数组不以任何方式排序。
在上述数据结构中,SEARCH 是通过对每个数组进行一系列二分查找来执行的。INSERT 通过一系列相同长度的数组合并执行,直到到达一个空数组。
更多细节:假设我们有一个长度为 2^k 的垂直数组,并且该数组的每个节点都附有长度为 2^k 的水平数组。
即垂直数组的第一个节点连接一个长度为2^0=1的水平数组,垂直数组的第二个节点连接一个长度为2^1=2的水平数组,以此类推。所以插入首先在第一个水平数组中执行,对于第二次插入,第一个数组变为空,第二个水平数组充满 2 个元素,第三次插入第一个和第二个数组水平。数组被填充等等。我为搜索和插入实现了正常的二进制搜索,如下所示:
int main()
{
int a[20]= {0};
int n, i, j, temp;
int *beg, *end, *mid, target;
printf(" enter the total integers you want to enter (make it less then 20):\n");
scanf("%d", &n);
if (n >= 20) return 0;
printf(" enter the integer array elements:\n" );
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
// sort the loaded array, binary search!
for(i = 0; i < n-1; i++)
{
for(j = 0; j < n-i-1; j++)
{
if (a[j+1] < a[j])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf(" the sorted numbers are:");
for(i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
// point to beginning and end of the array
beg = &a[0];
end = &a[n]; // use n = one element past the loaded array!
// mid should point somewhere in the middle of these addresses
mid = beg += n/2;
printf("\n enter the number to be searched:");
scanf("%d",&target);
// binary search, there is an AND in the middle of while()!!!
while((beg <= end) && (*mid != target))
{
// is the target in lower or upper half?
if (target < *mid)
{
end = mid - 1; // new end
n = n/2;
mid = beg += n/2; // new middle
}
else
{
beg = mid + 1; // new beginning
n = n/2;
mid = beg += n/2; // new middle
}
}
// find the target?
if (*mid == target)
{
printf("\n %d found!", target);
}
else
{
printf("\n %d not found!", target);
}
getchar(); // trap enter
getchar(); // wait
return 0;
}
谁能建议如何修改这个程序或一个新程序来实现如上所述的动态二进制搜索!