4个元素数组中的两个最大数字

时间:2014-11-07 16:13:28

标签: arrays algorithm assembly

我正试图找到一种方法来找到4个元素数组中最大的两个数字,我现在使用的方法是这样的:

开始
x = array[1]  
y = array[2]  
compare x,y  
if y > x then switch the values "because i want x to have the greatest value"  
read array[3] if it greater than x then make it the new x and give x value to y  
else if check if it greater than y if yes then make it the new y  

但是有太多的比较,我想减少它。你们有更好的算法吗?

4 个答案:

答案 0 :(得分:1)

是的,实际上你会为每个索引进行大量的比较。 为什么根本找不到最大值,将其从数组中删除然后找到最大值?

你的算法将是O(2n)所以O(n)

答案 1 :(得分:1)

比较最优算法使用4次比较。设元素为a,b,c,d。比较a和b,以及c和d。设e为a和b中的较大者,f为较小者。设g是c和d中的较大者,h是较小的。最大值是e和g中的较大者。如果是e,则第二个最大值是f和g中的较大者。如果是g,则第二个最大值是e和h中的较大者。

答案 2 :(得分:0)

您想减少使用说明吗?如在程序中使用较少或您少写?我将假设先前的。

把它想象成一棵树。

要获得最高价值,您可以使用少至3次比较

一个
...... \ ____ E
... / ........... \
乙.............. \
.................. \ ______最高
.................. /
................. /
ç............. /
...... \ ____ G
... /
d

要获得第二高的节点,您只需要将丢失的节点与最高节点进行比较。

实施例
A被发现是最高的,因此我们必须比较B和G以找到第二高。

结果:只需要4条指令

答案 3 :(得分:0)

在此阵列上执行bubblesort只需要进行6次比较。因为您只对2个最大的数字感兴趣,所以您可以在第二次迭代后立即缩短排序算法,从而避免第六次比较。
为了提高性能,将数组放入寄存器EAX,EBX,ECX和EDX

cmp eax,ebx
jl t1
xchg eax,ebx
t1:
cmp ebx,ecx
jl t2
xchg ebx,ecx
t2:
cmp ecx,edx
jl t3
xchg ecx,edx
t3:
cmp eax,ebx
jl t4
xchg eax,ebx
t4:
cmp ebx,ecx
jl t5
xchg ebx,ecx
t5:              ;ECX and EDX are the largest numbers