Couldn't understand the working of Kth smallest element in an array

Viewed 42

enter image description here

Code snippet function to find the kth smallest element in an array

{
    vector <int> ans(arr, arr+r+1);

    sort(ans.begin(), ans.end());

    return ans[k-1];
}

I am unable to understand the working of this code, please explain

1 Answers

The shown code does the following.

  1. It defines a variable with the name "ans" of type std::vector. In C++ people usually do not use C-Style arrays but more so called container, like std::vector or std::array. The feature-set of such containers is much better than that of plain C-style arrays

  2. In C++ you can use so called "constructor"s which may initialize classes with values.

  3. The std::vector has many constructors, one of them is the range constructor (5). This will copy a range of values, from the begin of an area to the end of an area into the vector

  4. So, in your case, r+1 values from the C-style array will be copied into the vector.

  5. With sort(ans.begin(), ans.end()); the values in the std::vector will be sorted in ascending sequence.

  6. Since the values are sorted, the smallest values will be at the beginning.

  7. Caveat. The indices for array-like types in CPP start with index 0. Hence you see k-1

Example: If you want to have the 3rd smalles value, then k=3. And the value with index k-1, so, 2, will be accessed

Having orignal array with values 5,4,3,2,1, after the sorting we will have 1,2,3,4,5 with

Index:  0   Value 1
Index:  1   Value 2
Index:  2   Value 3
Index:  3   Value 4
Index:  4   Value 5

So, selecting value at index 2, will give you the expected result 3.

Related