Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

random select algo

# ------------------- Randomized selection
def swap(A, i, j):
	A[i], A[j] = A[j], A[i]

def partition(A, p, r):
    pivot = A[r]
    i = p - 1
    for j in range(p, r):
        if A[j] <= pivot:
            i += 1
            swap(A, j, i)
    swap(A, i+1, r)
    print(A, i+1, pivot)
    return i + 1  # index of the new position of the pivot which is his good position in the sorted array


def randomized_partition(A, p, r):
    randomidx = random.randrange(r-p+1) + p
    swap(A, randomidx, r)
    return partition(A, p, r)


def randomized_selection(A, p, r, s):  # s is the nth element of the arr sorted ex: s=2 => A[1]
  #p is the index of the first element/ r the last
    if p == r:
        print(A)
        return A[p]
    q = randomized_partition(A, p, r)
    k = q - p + 1 # length between p and q
    print(f"q:{q}, k:{k}, s:{s}, p:{p}, r:{r}")
    if s == k:
        print(A)
        return A[q]
    elif s < k:
        return randomized_selection(A, p, q - 1, s)
    else:
        return randomized_selection(A, q + 1, r, s-k)

#-----------Code 
li =[6, 2, 7, 4, 9, 1, 5, 8, 3, 6]
print(randomized_selection(li, 0, 9, 3))
# The 3rd element is 3
#sorted li : [1, 2, 3, 4, 5, 6, 6, 7, 8, 9]
Comment

PREVIOUS NEXT
Code Example
Python :: interpoltaion search formula python 
Python :: pyspark create empty dataframe 
Python :: load from np file py 
Python :: python year month from date 
Python :: python f string thousand separator 
Python :: mouse in pygame 
Python :: close turtle window python 
Python :: python check if list contains elements of another list 
Python :: python remove text between parentheses 
Python :: how to find where python is located 
Python :: reduced fraction python 
Python :: brownie get active network 
Python :: install auto-py-to-exe 
Python :: python spammer messages 
Python :: rotate matrix 90 degrees clockwise python 
Python :: downgrade pip 
Python :: area of a circle in python 
Python :: opening image in python 
Python :: python method to filter vowels in a string 
Python :: to int in pandas 
Python :: how to read input from stdin in python 
Python :: square (n) sum 
Python :: pandas predict average moving 
Python :: python decimal number into 8 bit binary 
Python :: python iterate object 
Python :: python return -1 
Python :: Removing punctuation with NLTK in Python 
Python :: regex to find ip address python 
Python :: how to provide default value when assign i ngvariables python 
Python :: worksheet merge&center cells python 
ADD CONTENT
Topic
Content
Source link
Name
4+5 =