Advertisement
rishu110067

Untitled

Jan 31st, 2022
1,079
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 KB | None | 0 0
  1. from collections import Counter
  2.  
  3. def kth_largest_in_an_array(numbers, k):
  4.  
  5.     import random
  6.     kthindex=len(numbers)-k
  7.     start=0
  8.     end=len(numbers)-1
  9.    
  10.     def helper(start,end):
  11.        
  12.         if start==end:
  13.             return
  14.        
  15.         pivot=random.randint(start,end)
  16.        
  17.         numbers[start],numbers[pivot]=numbers[pivot],numbers[start]
  18.  
  19.         # elemenst less than numbers[pivot] will be placed before pivotloc1
  20.         # elemenst equal to numbers[pivot] will be placed between pivotloc1 and pivotloc2
  21.         # elemenst greater than numbers[pivot] will be placed after pivotloc2
  22.         pivotloc1 = start
  23.         pivotloc2 = start
  24.         for i in range(start+1,end+1):
  25.             if numbers[i] < numbers[start]:
  26.                 pivotloc1+=1
  27.                 pivotloc2+=1
  28.                 numbers[pivotloc1],numbers[i]=numbers[i],numbers[pivotloc1]
  29.             elif numbers[i] == numbers[start]:
  30.                 pivotloc2+=1
  31.                 numbers[pivotloc2],numbers[i]=numbers[i],numbers[pivotloc2]
  32.                
  33.         numbers[start],numbers[pivotloc1]=numbers[pivotloc1],numbers[start]
  34.        
  35.         # kth largest element is equal to numbers[pivot] if kthindex is between pivotloc1 and pivotloc2
  36.         if pivotloc1 <= kthindex and kthindex <= pivotloc2:
  37.             return
  38.         elif pivotloc2 > kthindex:
  39.             helper(start,pivotloc2-1)
  40.         else:
  41.             helper(pivotloc1+1,end)
  42.        
  43.     helper(start,end)    
  44.     return numbers[kthindex]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement