kth smallest element in array

This is continuation of sorting of array elements. Please go through this blog . In that blog, sorting of array elements is explained along with code. In order to find out kth smallest or kth largest element in array having all distinct elements , we need to sort this array first .Once sorting is done , then it is straight forward to get kth element (smallest or largest element) using a[k-1]
Here I am sharing code for smallest kth element of an array. For kth largest element is achieved through descending sorting.

arr=(4 3 2 1) ## Array of 4 Elements
len=${#arr[@]}
n=0
k=2
lngthminusone=$(( $len -1))
while [ $n -lt $len ]
do
i=0
while [ $i -lt $lngthminusone ]
do
j=$(( $i + 1))
if [ ${arr[i]} -gt ${arr[j]} ]
then
temp=${arr[i]}
arr[i]=${arr[j]}
arr[j]=$temp
fi
i=$(( $i + 1))
done
n=$(( $n + 1))
done
echo ${arr[*]}
echo "kth Element is " ${arr[k-1]}


Related posts