同时最大和最大最小的一组元素

时间:2011-09-24 14:17:51

标签: algorithm

在第9.1节中提到的“同时最大值和最大值”中提到的“算法简介 - 通过CLRS”。最小查找可以在3 * floor(n / 2)的运行时间内完成。与下限相同。

我编写了以下算法(从CLRS获取帮助),其下限是2 * floor(n / 2)。 [这是错的 - 感谢Ricky Bobby]

I m using the variables: 'max' & 'min' to denote maximum & minimum elements, 'i' as indexing variable.

Simultaneous_Maximum_&_Minimum (A, n)  // Array A[1...n]
{
  1. If n is even, compare the first two elements and assign the larger to max and
      smaller to min. Set StartIndex = 3.

  2. If n is odd, set both max & min to the first element. Set StartIndex = 2.

  3. for (i = StartIndex; i <= n; i = i+2 ) {  // Processing elements in pair

         if (max < A[i]) {          // Compare max with A[i]
               if (A[i] < A[i+1])   // Compare max with A[i+1]
                     max = A[i+1];  // we sure that A[i] or A[i+1] can't be min

               else {                 // When max less than A[i] but A[i] not less than A[i+1]
                     max = A[i];        // Set A[i] as max
                     if (min > A[i+1])  // Possible that A[i+1] can be min
                          min = A[i+1]; // if yes, set A[i+1] as min
               }
         }

            // When max is not less than A[i]
         else if (min > A[i]) {        // Compare min with A[i]
                     if (A[i] > A[i+1])  // Compare min with A[i+1]
                           min = A[i+1]; // we sure that A[i] or A[i+1] can't be max

                     else {             // When min is greater than A[i] but A[i] not greater than A[i+1]
                           min = A[i];       // Set A[i] as min
                           if (max < A[i+1]) // Possible that A[i+1] can be max
                                max = A[i+1] // if yes, set A[i+1] as max
                     }
                }                    
         }

         else {  // max > A[i] and min < A[i] -- so A[i] can't be max or min

              if (max < A[i+1])
                  max = A[i+1]

              if (min > A[i+1])
                  min = A[i+1] 
         }
     }
}

感谢Ricky Bobby指出我的错误 - 我们无法找到同时的最大值&amp;至少2 *楼(n / 2)运行时间。

2 个答案:

答案 0 :(得分:2)

告诉我,如果我错了,但你不看案例:max&gt; A [i]&gt; min

if max>A[i]>min :
   if A[i+1] > max 
       max =A[i+1]
   if A[i+1] <min 
       min = A[i+1]

所以你的算法在一般情况下是错误的。

按递减顺序或增加顺序它可能有效,但它没有用,因为对于排序列表,你可以找到这个表达式的最小值和最大值:

(min,max) = (A[0],A[n]).sort()

所以在O(get(A [0])+ get(A [n]))

答案 1 :(得分:-1)

如果数组已排序,则可以在数组[0]找到最小值,在数组[n-1]找到最大值。或者反过来降序。