Home > Mobile >  Kth smallest element in a array
Kth smallest element in a array

Time:02-01

I was writing this code for finding Kth smallest element in array where l= starting index and r = ending index is given to us as input parameter in function.

class Solution{
    public:
    int kthSmallest(int arr[], int l, int r, int k) {
        //code here
        arr.sort(l,l r 1);
        int count =1,i=1,var =0;
        while(count<=k)
        {
            var = arr[i];
            count  ;
            i  ;
        }
        return var;
    }
};

I tried to use sort function in my code but this code is giving error in my sort function ,given below which is not understood by me.

prog.cpp: In member function int Solution::kthSmallest(int*, int, int, int):

prog.cpp:18:13: error: request for member sort in arr, which is of non-class type int*

     arr.sort(l,l r 1);
         ^

CodePudding user response:

In C , arrays like arr are not objects, so they have no members like sort that you can access using the dot operator.

Instead, try using std::sort from the <algorithm> header:

#include <algorithm>

std::sort(arr   l, arr   r   1);

This example assumes that:

  • l is the leftmost index you're sorting.
  • r is the rightmost index.
  • both l and r are valid indices for arr.

CodePudding user response:

arr is type int *, so a primitive type and a primitive type don't have any member function. So arr don't have any sort() member function, so it cause an error.

If you want to sort arr, use std::sort from <algorithm>.

std::sort(arr   l, arr   r   1);

CodePudding user response:

Another way is to use the std::nth_element algorithm, it will give you the element at the position in the array if the array where sorted. To use it you need iterator so you will have to convert your C array arr[] into a std::array if you don't want heap allocation or a std::vector if you want to be more flexible.

Note: if you use C 20 you can use std::ranges::nth_element

  •  Tags:  
  • Related