c# - 大O分析。非负数组中的最大整数

标签 c# c arrays algorithm

<分区>

尝试做大O分析- 这个程序的平均情况是什么? O(n/2(n/2)) = O(n^2) ?..

 /* Returns the largest integer in the array */
 int CompareToAll(int array[], int n)
 {

   int  i, j;
   bool isMax;/* Make sure that there is at least one element in the array.*/                        

   if (n <= 0) return -1;

   for (i = n-1; i > 0; i--) 
   {
      isMax = true;
      for (j = 0; j < n; j++) {

        /* See if any value is greater.*/
         if (array[j] > array[i]){
             isMax = false;  /* array[i] is not the largest value. */
             break;
          }
      } /* If isMax is true, no larger valueexists; array[i] is max. */

      if (isMax)
        break;
   }
   return array[i];
}

谢谢

最佳答案

是的,平均来说是 O(n2),假设元素是随机选择的。在最坏的情况下,您将每个元素与其他所有元素进行比较。

这个算法不是最优的。可以使用简单的 O(n) 算法找到数组中的最大元素:遍历数组一次,同时跟踪到目前为止看到的最大元素。

关于c# - 大O分析。非负数组中的最大整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13314177/

相关文章:

c - 如何获取char*的子串

c - 对 AVR 进行编程以解释 Arduino 旋转编码器模块的输入时出现问题

ruby - 在 Ruby 对象类中创建数组

javascript - 一个数组还是多个? (哈希表)

C - __declspec(thread) 变量性能

c - 使用结构体指针的两个函数(读取和显示数组)

c# - 在 C# 中通过名称查找后台工作对象

c# - 如何刷新 Metro Style 应用程序的 UI?

c# - 检查程序集的版本而不加载它

c# - 加快 linq/实体结果的返回速度