Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

How can one find the three largest values of an input array efficiently, namely without having to sort the input array?

"""
This implementation finds the three largest
numbers in an array in an efficient manner.

The idea is to maintain a subarray holding
the three largest values encountered so 
far. When the algorithm concludes that 
subarray would end up holding the desired
output value (i.e., 3 largest values of 
main array).

Let n be the size of the array
Time complexity: O(n)
Space complexity: O(1)
"""
def find_three_largest_values(arr):
    # Container for 3 largest values
    result = [None]*3
    # Make sure result holds always
    # 3 largest values encountered so far
    for val in arr:
        update_result(result, val)
    return result

def update_result(result, val):
    # Insert val into appropriate position
    # Only vals of interest are those bigger
    # than values already in result array.
    if result[2] is None or val > result[2]:
        update_and_shift(result, val, 2)
    elif result[1] is None or val > result[1]:
        update_and_shift(result, val, 1)
    elif result[0] is None or val > result[0]:
        update_and_shift(result, val, 0)

def update_and_shift(result, val, idx):
    for i in range(idx+1):
        if i == idx:
            result[i] = val
        else:
            result[i] = result[i+1]

arr = [1, 2, 3, 7, 8, 9]
print(find_three_largest_values(arr))  # [7, 8, 9]
Comment

PREVIOUS NEXT
Code Example
Python :: json load python 
Python :: add empty row to pandas dataframe 
Python :: python system of equations 
Python :: append to csv python 
Python :: python webdriver element not interactable 
Python :: get the system boot time in python 
Python :: python loop certain number of times 
Python :: drop na in pandas 
Python :: ec2 upgrade python 3.7 to 3.8 
Python :: array search with regex python 
Python :: how to get user input of list in python 
Python :: python selenium assert presence of an element 
Python :: model.predict([x_test]) error 
Python :: how to read a .exe file in python 
Python :: add column names to dataframe pandas 
Python :: django querset group by sum 
Python :: make a specific column a df index 
Python :: python datetime last day of month 
Python :: godot string format 
Python :: pandas search for nan in column 
Python :: Pyo example 
Python :: python snake game 
Python :: text to pandas 
Python :: bisect_left in python 
Python :: python: select specific columns in a data frame 
Python :: how to display a manytomany field in django rest framework 
Python :: Python program to print odd numbers in a list 
Python :: iterar una lista en python 
Python :: holidays python 
Python :: python numpy arrays equality 
ADD CONTENT
Topic
Content
Source link
Name
6+2 =