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…

# Tag: if in shell

## 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) ##…

## Missing element in an Array

Consider a Array of N-1 elements which has values from 1 to N which means one of the element is always missing. So, In this Blog, sharing the code for the same.For Example a=( 4 3 2 5) , here number of elements is N-1 which means 4 and values ranges from 1 to N(which means 5) and hence we need to print that missing element or number is 1. arr=(4 3 2 5) ## Array of 4 elements(N-1)len_arr_1=$(( ${#arr[@]} +1)) ##Making length equal to N (5)len_arr=${#arr[@]} ## Traversing all…