How do you find the kth smallest element in an array in python?

Given an array and a number K where K is smaller than the size of the array. Find the K’th smallest element in the given array. Given that all array elements are distinct.

Examples:  

Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 
Output: 7

Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 4 
Output: 10 

We have discussed a similar problem to print k largest elements. 

K’th smallest element in an unsorted array using sorting:

Sort the given array and return the element at index K-1 in the sorted array. 

Follow the given steps to solve the problem:

  • Sort the input array in the increasing order
  • Return the element at the K-1 index [0 – Based indexing] in the sorted array

Below is the Implementation of the above approach:

C

#include

#include

int cmpfunc[const void* a, const void* b]

{

    return [*[int*]a - *[int*]b];

}

int kthSmallest[int arr[], int N, int K]

{

    qsort[arr, N, sizeof[int], cmpfunc];

    return arr[K - 1];

}

int main[]

{

    int arr[] = { 12, 3, 5, 7, 19 };

    int N = sizeof[arr] / sizeof[arr[0]], K = 2;

    printf["K'th smallest element is %d",

           kthSmallest[arr, N, K]];

    return 0;

}

C++

#include

using namespace std;

int kthSmallest[int arr[], int N, int K]

{

    sort[arr, arr + N];

    return arr[K - 1];

}

int main[]

{

    int arr[] = { 12, 3, 5, 7, 19 };

    int N = sizeof[arr] / sizeof[arr[0]], K = 2;

    cout

Chủ Đề