Simultaneous minimum and maximum (Solution to algorthm)

来源:互联网 发布:淘宝购买电影资源 编辑:程序博客网 时间:2024/04/27 23:07

if we want to get both  the Min and Max number from the unsorted sequence ,and we want it's less than 2n comparisions.

so we can get it at most 3(n/2) comparisions;

And it is the algorthm followed:(pseudocode)

MIN_MAX(A)

if  A[1]>A[2]   then min = A[2],max = A[1];
                      else min = A[1].max = A[2];
m = n/2;
for i = 2; to m;
 if A[2i-1] > A[2i]
       then if A[2i] < min then min = A[2i];
               if A[2i-1]>max then max = A[2i-1];
    //(A[2i-1]<=A[2i])    
 else if A[2i-1] <min then min = A[2i-1];
          if  A[2i[>max   then max = A[2i];
if n != 2m then if A[n]<min then min = A[n];
                          if A[n]>max then max = A[n];
return (min ,max);


原创粉丝点击