Consider an Array (2 4 1 3 5). Inversions are those pairs where a[i]>a[j] and i<j . For above mentioned array, below are the pairs of Inversions. So, total Count Inversions are 3 for this Array.(2 1)(4 1)(4 3)Below is the code for the same using shell scripting. a=(2 4 1 3 5)len=${#a[@]}lngthminusone=$(( $len -1))i=0## This while loop will run inner loop for each element.while [ $i -lt $len ] doj=0## This while loop will compare one element with rest of the elements.while [ $j -lt $lngthminusone ] doj=$(( $j…
Day: December 3, 2022
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…