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…

Groups in Array

Consider an array of length N (1 2 4 5 10) and k=3. Below are the groups of Arrays(1 2 4) and (5 10)There is a difference between sub-array and groups in array. They are not at all same.Sub Array of k=3 are following.(1 2 4) , (2 4 5) and (4 5 10) In this blog, we are discussing about groups in array not sub-array. a=(1 2 4 5 10)len1=${#a[@]}j=0i=1##Set the value of K herek=3##Get the number of Groups of Array a(( NoOflps=(len1+k-1)/k ))echo $NoOflps##Run the innner while loop…

Rearrange array alternatively

Consider an array (for example (1 3 2 4 6 12))of even number of elements like 2,4 or any number which is even . Need to arrange array in below order.First maximum First Minimum Second Max Second Min Third Max Third Min…. I have divided code into 4 parts.## Arrange elements in Descending order and create a blank array newlist of same length with value 0## arr=(1 3 2 4 6 12)len=${#arr[@]}k=0newlist=()lngthminusone=$(( $len -1))echo $lngthminusonewhile [ $k -lt $len ]doi=0value=0newlist+=$valuewhile [ $i -lt $lngthminusone ]doj=$(( $i + 1))if [ ${arr[i]}…

All Sub Array having sum=0

In this blog, first we need to understand sub array definition and code to find sum of all Sub-Array in an Array. For that, please refer to this blog. Now, we need to find all Sub-Array whose Sum is equal to zero. Consider an array (1 -1 2 1 -3) and there are three sub-array whose sum is zero mentioned below.( 1 -1)(2 1 -3)(1 -1 2 1 -3) Below is the Shell Script which will give all sub-array whose sum is 0 . arr=(1 -1 2 1 -3) ##…

Sum of all Array Elements in Linux

In this Blog, Sharing the code to add all elements of an Array using shell scripting. a =(1 2 3 4) ## Array of 4 Elementsi=0len=${#a[@]} ## It gives the length of an Arraysum=0 ## Setting sum variable to value 0while [ $i -lt $len ]dosum=$((${a[i]}+$sum))i=$(( $i + 1))doneecho $sum

Shell script to run for x hours using while Loop

Today i will discuss about the shell script code snippet which will run for x hours. Below is the code snippet which will help you to run code for x hours. ## Here I am using 10 seconds , in order to run for 1 hours, mention the same in seconds which is 3600. $vartime value will be set to 3600 initially. vartime=$((SECONDS+10)) echo $vartime ## $SECONDS tells you the time period for which script is running.Initially it will be 0 seconds when script starts. So, 0 will be compared…