所有数组元素的比较 - Ç算法 [英] Comparison of all array elements - C algorithm
本文介绍了所有数组元素的比较 - Ç算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个矩阵的 M 的*的 N 的和,对于每一行,我需要的所有元素当中比较。
对于每对夫妇,我觉得,我会打电话给该会执行一些计算功能。
I have a matrix m * n and, for each row, I need to compare all elements among them. For each couple I find, I'll call a function that is going to perform some calculations.
例如:
my_array -> {1, 2, 3, 4, 5, ...}
I take 1 and I have: (1,2)(1,3)(1,4)(1,5)
I take 2 and I have: (2,1)(2,3)(2,4)(2,5)
and so on
用C我写这样的:
Using C I wrote this:
for (i=0; i<array_length; i++) {
for (k=0; k<array_length; k++) {
if (i==k) continue;
//Do something
}
}
}
我想知道如果我可以使用算法复杂度低。
I was wondering if I can use an algorithm with lower complexity.
推荐答案
没有,这是为O(n ^ 2)的定义[长在这里解释,但请相信我( - :]结果
但是你可以通过减少一半的迭代次数:
No, it's O(n^2) by definition [ to long to explain here, but trust me (-: ]
But you can decrease the number of iterations by half :
for (i=0; i<array_length; i++) {
for (k=i+1; k<array_length; k++) { // <-- no need to check the values before "i"
//Do something
//If the order of i and k make a different then here you should:
//'Do something' for (i,k) and 'Do something' for (k,i)
}
}
}
这篇关于所有数组元素的比较 - Ç算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文