Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python randomized selection

# ------------------- 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 :: python pie chart with legend 
Python :: wtf forms required 
Python :: python split string capital letters 
Python :: python year from date 
Python :: decode url python 
Python :: how to find the lowest value in a nested list python 
Python :: tkinter draw circle 
Python :: tf.squeeze() 
Python :: matplotlib x axis at the top 
Python :: Add help text in Django model forms 
Python :: simplify fractions python 
Python :: argument sequence in python function 
Python :: how to rotate x axis labels in subplots 
Python :: python WhatsApp messaging spammer 
Python :: update link python is python 3 
Python :: Function to a button in tkinter 
Python :: get median of column pandas 
Python :: where my python modules in linux 
Python :: how to make a url shortener in python 
Python :: how to check if an element is visible on the web page in selenium python 
Python :: input stdout python 
Python :: check column type pandas 
Python :: rolling average df 
Python :: find out current datetime in python 
Python :: python convert 1 to 01 
Python :: python dict to url params 
Python :: Removing punctuation in Python 
Python :: strftime python 
Python :: corona shape in python 
Python :: arweave python 
ADD CONTENT
Topic
Content
Source link
Name
3+9 =