[英]comparisons using merge sort vs selection sort
我有一個10 int的數組,並使用選擇排序我計算它需要大約45個比較來整理整個數組,但我不確定通過我的計算使用合並排序進行排序需要多少才需要進行12次比較...我在這里是對還是錯?
提前致謝
這是合並方法
static void merge(int[] first, int[] second, int[] a)
{
int iFirst = 0;
int iSecond = 0;
int i = 0;
//moving the smaller element into a
while(iFirst < first.length && iSecond < second.length)
{
if(first[iFirst] < second[iSecond])
{
a[i] = first[iFirst];
iFirst++;
}
else
{
a[i] = second[iSecond];
iSecond++;
}
i++;
}
counter += i;
//copying the remaning of the first array
while(iFirst < first.length)
{
a[i] = first[iFirst];
iFirst++; i++;
}
//copying the remaining of second array
while(iSecond < second.length)
{
a[i] = second[iSecond];
iSecond++; i++;
}
}
要將n
元素數組與m
元素數組合並,在最壞的情況下需要進行n+m-1
比較(最佳n+m-1
min{m,n}
)。
因此,當您將10個元素的數組拆分為一半時,頂級合並最多需要進行9次比較。 兩個5個元素的一半最多需要4個比較,使得9 + 2*4 = 17
。 將2元素和3元素部分中的5個元素分成兩半需要最多1 + 3個比較,因此總體最差情況將是25個比較(9 + 2 * 4 + 2 * 3 + 2 * 1)。
10(9) 9
/ \
/ \
/ \
/ \
/ \
/ \
/ \
5(4) 5(4) 8
/ \ / \
/ \ / \
3(2) 2(1) 3(2) 2(1) 6
/ \ / \ / \ / \
2(1) 1 1 1 2(1) 1 1 1 2
/ \ / \
1 1 1 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.