DEV Community

Abirami Prabhakar
Abirami Prabhakar

Posted on

To Find the kth Smallest element in a array

lets first undertsand the question from

Given an integer array arr[] and an integer k, your task is to find and return the kth smallest element in the given array.

_sample i/p and o/p from a question
Input: arr[] = [7, 10, 4, 3, 20, 15], k = 3
Output: 7

Explanation: 3rd smallest element in the given array is 7._
we understand that the input array is sorted in ascending order and then the element in kth position in the array is returned by the function

how to approach the solution

I started with a question "How to sort an array without sort function ?" . so, I used the simplest sorting algorithm, Bubble Sort. The bubble sort works when the array is put in a for loop where elements two adjacent elements are swapped with they are not in order

ex : [5 ,2, 3 ]

loop 1: 5 > 2 -> swap [2,5,3]
loop 2 : 5 > 3 -> swap [2,3,5]

then the kth element from sorted array is returned
arr[k-1] -> kth element as the index value is always 1 more

def kthsmallest(arr,k):
    for i in range(len(arr)):
        for j in range(0, n-i-1):
            if arr[j] > arr[j+1]:
               #swapping of adjacent elements using bubble sort
                arr[j], arr[j+1] = arr[j+1], arr[j]

    return arr[k-1]
print(kthsmallest(arr,k)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)