[英]Worst and best case in making comparisons
給定兩個按升序排列的
double
值數組,一個數組包含100個元素,另一個數組包含10個元素,采用最佳算法將這些數組合並成一個排序的數組(在最佳情況下和最壞情況下)需要進行多少次比較案件?
答案是:
最佳案例:10個比較
最壞的情況:109比較
在將我標記為家庭作業問題或愚蠢問題之前,請聽我說完。 我將解釋自己的理由,並以標題為標題,就好像有人對迭代/比較有類似的問題,他們可以看看。
我了解10個比較的最佳情況,因為較短數組中的所有值都必須小於100值較大數組中的所有值。 然后,您將只進行一個比較並對其進行排序。
但對於最壞的情況,我無法進行109次比較。 我不知道問題是否要求使用合並排序進行比較,其中短數組中的每個數字都會進行7次比較(log2 ^ 100 = 6.64),而7乘以10則是70而不是109。
難道我做錯了什么? 這個問題的答案也無濟於事。 如果大家都能理解和解釋,將不勝感激。
即使有了答案,我也不明白如何進行比較以及使用哪種類型的排序(如果使用了排序)。 有人可以再看一次嗎?
在最壞的情況下,請考慮以下情況:
Array-1
: 1,2,3,4,5,6,7,8,9,110
。
Array-2
: 10,11,12,13,14,15,.....,109
。
合並這兩個數組的最佳方法是比較兩個數組的第一個元素(如果有),然后取最小的一個並在該數組中繼續進行。
因此,這里,如果我們計數總的比較, First 9
的元件Array-1
將被與第一元件相比Array-2
因為first
元件Array-2
大於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
,經過10
次比較, Array-1
將為空(采用所有元素)。 因此,將不再進行更多比較。 因此,最佳情況下的總比較為10
。
如果要打印任何輸入的總比較,請在算法中進行很少的更改。
定義一個變量int total_comparisons=0;
然后每次進行比較時,都要增加它。 因此,請更改比較條件:
if(total_comparisons++ && array1[point1]>array2[point2]) //This is to be counted as a comparison
然后最后打印total_comparisons
。 這是您了解邏輯的更好方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.