Advertisement
imashutosh51

Kth Smallest element

Jul 31st, 2022 (edited)
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. //Method 1
  2. /*
  3. Time complexity: O(nlogk)
  4. Auxiliary Space: O(logK)
  5.  
  6. max_heap will store maximum of k minimum elements of the array
  7. */
  8. class Solution{
  9.     public:
  10.     int kthSmallest(int arr[], int l, int n, int k) {
  11.             priority_queue<int> pq;
  12.             for(int i = 0; i < k; i++)  pq.push(arr[i]);
  13.             for(int i = k; i <=n; i++){
  14.                 if(arr[i] < pq.top()){  //it is because we will keep k minimum elements in max_heap and maximum of that k we will be at top
  15.                     pq.pop();           //that will be our answer ie. kth minimum element
  16.                     pq.push(arr[i]);
  17.                 }
  18.             }
  19.             return pq.top();
  20.     }
  21. };
  22.  
  23. //Method 2
  24. //Quick select
  25. int partition(int arr[],int l,int r){
  26.     int pivot=arr[r];
  27.     int i=l,j=l;
  28.     for(;i<r;i++){
  29.         if(arr[i]<pivot){ swap(arr[i],arr[j]); j++;}
  30.     }
  31.     swap(arr[j],arr[r]);
  32.     return j;
  33. }
  34. int quickselect(int arr[],int l,int r,int k){
  35.     if(l<=r){
  36.         int p=partition(arr,l,r);  
  37.         if(k==p) return arr[k];
  38.         if(k<p) return quickselect(arr,l,p-1,k);
  39.         else return quickselect(arr,p+1,r,k);
  40.     }
  41. }
  42. class Solution{
  43.     public:
  44.     // arr : given array
  45.     // l : starting index of the array i.e 0
  46.     // r : ending index of the array i.e size-1
  47.     // k : find kth smallest element and return using this function
  48.     int kthSmallest(int arr[], int l, int r, int k) {
  49.         //find element at k-1 position
  50.         return quickselect(arr,l,r,k-1);
  51.     }
  52. };
  53.  
  54.  
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement