考虑最坏的情况
Array-1:1,2,3,4,5,6,7,8,9,110。
Array-2:10,11,12,13,14,15,.....,109。
合并它们的最佳方法是比较两个数组的第一个元素(如果可用),然后取最小值并在该数组中进一步处理。
所以在这里,如果我们计算总比较,Array-1 的 First 9 元素将与 Array-2 的第一个元素进行比较,因为 Array-2 的 first 元素大于 first 9 的元素 Array-1 所以Total Comparisons = 9 到现在。
现在array-1 的最后一个元素是所有元素中最大的,因此很明显它最终会在合并中出现,但array-2 中存在all 元素,它们将与array-1 的元素进行比较。
所以这将总共进行100 比较。现在Total Comparisons = 100 + 9 = 109。所以在这种情况下,最坏的情况最多有 109 比较。
编辑:
合并代码:
Merge(int array1[],int array2[])
{
int array3[]=new int[array1.length+array2.length];
int point1=0; //indicating current element of array1
int point2=0; //indicating current element of array2
int point3=0; //indicating current element of resultant array3
while(point1<array1.length && point2<array2.length)
{
if(array1[point1]>array2[point2]) //This is to be counted as a comparison
{
array3[point3]=array2[point2]; //Take element of array2
point2++; //move to the next element of array2
point3++; //move to the next element of array3
}
else
{
array3[point3]=array1[point1]; //Take element of array3
point1++; //move to the next element of array1
point3++; //move to the next element of array2
}
}
while(point1<array1.length)
{
array3[point3]=array1[point1]; //Take element of array3
point1++; //move to the next element of array1
point3++; //move to the next element of array2
}
while(point2<array2.legnth)
{
array3[point3]=array2[point2]; //Take element of array2
point2++; //move to the next element of array2
point3++; //move to the next element of array3
}
}
所以这里我们比较两个数组的元素时,是要算作比较的。为了最好的情况,
Array-1 = 1,2,3,4,5,6,7,8,9,10.
Array-2 = 11,12,13,14,.....,110.
所以这里的总比较将是10,在10th 比较之后,Array-1 将变为空(所有元素都被取走)。所以不再做进一步的比较。因此,最佳情况下的总比较是10。
如果您想打印任何输入的总比较,请对算法进行一些更改。
定义一个变量int total_comparisons=0;,然后每次进行比较时,将其递增。所以改变比较条件:
if(total_comparisons++ && array1[point1]>array2[point2]) //This is to be counted as a comparison
然后最后打印total_comparisons。这是您理解逻辑的更好方法。