Can I find the maximum / minimum value in an unsorted array in sublinear time?

Is it possible? If not, specify an array of size n, how do you know if it is better to sort the array?

+5
source share
4 answers

With just an unsorted array, there is no way to do this in sublinear time. Since you do not know which element is the largest and smallest, you must look at them all, therefore, at linear time.

The best variety you find will be worse than probably relatively n log n, so it will be β€œbetter" to perform a linear scan.

, . , :

  • min max. O (1).
  • min max , . O (1).
  • min max "unknown", min max. O (1). , min/max, . , , , , . , .
  • , . O (1).
  • , , . O (1).
  • , , , , . O (n).

, , min/max . , , .

, , , min/max .


, :

def initList ():
    list = []
    maxval = 0
    maxcount = 0

. .

, :

def addToList (val):
    list.add (val) error on failure

    # Detect adding to empty list.
    if list.size = 1:
        maxval = val
        maxcount = 1
        return

    # If no maximum known at this point, calc later.
    if maxcount = 0:
        return

    # Adding less than current max, ignore.
    if val < maxval:
        return

    # Adding another of current max, bump up count.
    if val = maxval:
        maxcount += 1
        return

    # Otherwise, new max, set value and count.
    maxval = val
    maxcount = 1

. . , . , , - , , , .

, , , ( ):

def delFromList (val):
    list.del (val) error on failure

    # Decrement count if max is known and the value is max.
    # The count will become 0 when all maxes deleted.
    if maxcount > 0 and val = maxval:
        maxcount -= 1

- , , ( maxcount ). , :

def getMax ():
    # raise exception if list empty.
    error if list.size = 0

    # If maximum unknown, calculate it on demand.
    if maxcount = 0:
        maxval = list[0]
        for each val in list:
            if val = maxval:
                maxcount += 1
            elsif val > maxval:
                maxval = val
                maxcount = 1

    # Now it is known, just return it.
    return maxval

, , -, , list, maxval maxcount. , , , .

+5

:

/ ?

, .

, min max //, min/max .

, min max, , . (, insert/append/replace, .)

+5

min/max O (N). . 0 (1), 0 (N log N). min/max , , . , , Rb-tree heap, , .

+2

( ++), - - com - , 3n/2 - 2, n ( - 3/2).

2 ( 3/2 -2), n, , , O (n) , ( ), 1,5

0

All Articles