Home > other >  kth smallest inetger value?
kth smallest inetger value?

Time:03-06

Given an array arr[] and an integer K where K is smaller than size of array, the task is to find the Kth smallest element in the given array. It is given that all array elements are distinct

def kthSmallest(self,arr,k):
    def k1(arr):
         res=arr[0]
         for i in range(1,len(arr)-1):
            if res>arr[i]:
                res=arr[i]
         return res
    if k==1:
        k1(arr)
    elif k==2:
        a=k1(arr)
        arr.remove(a)
        return k1(arr)
        
    else:
        for i in range(k-1):
          a=k1(arr)
          del a
        return k1(arr)
l=[7,10,4,3,20,15]
k=3
print(kthsmallest(l,k))

CodePudding user response:

An easy way is to sort the array (or in your case, the list)

kthsmallest = sorted(arr)[K-1]

CodePudding user response:

Why not just do it by sorting the array?

def kthSmallest(arr, k):
    arr.sort(reverse=False)
    return arr[k - 1]
  • Related