我有一个矩阵的 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) } } }