Queries to find minimum swaps required to sort given array with updates | C # program for the above approach ; Function to return the position of the given value using binary search ; Return 0 if every value is greater than the given value ; Return N - 1 if every value is smaller than the given value ; Perform Binary Search ; Iterate till start < end ; Find the mid ; Update start and end ; Return the position of the given value ; Function to return the number of make the array sorted ; Index x to update ; Increment value by y ; Set newElement equals to x + y ; Compute the new index ; Print the minimum number of swaps ; Driver Code ; Given array [ ] arr ; Given Queries ; Function Call
using System ; using System . Collections . Generic ; class GFG { static int computePos ( int [ ] arr , int n , int value ) { if ( value < arr [ 0 ] ) return 0 ; if ( value > arr [ n - 1 ] ) return n - 1 ; int start = 0 ; int end = n - 1 ; while ( start < end ) { int mid = ( start + end + 1 ) / 2 ; if ( arr [ mid ] >= value ) end = mid - 1 ; else start = mid ; } return start ; } static void countShift ( int [ ] arr , int n , List < List < int > > queries ) { foreach ( List < int > q in queries ) { int index = q [ 0 ] ; int update = q [ 1 ] ; int newElement = arr [ index ] + update ; int newIndex = computePos ( arr , n , newElement ) ; Console . Write ( Math . Abs ( newIndex - index ) + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 3 , 4 , 5 , 6 } ; int N = arr . Length ; List < List < int > > queries = new List < List < int > > ( ) ; List < int > v = new List < int > ( ) ; List < int > v1 = new List < int > ( ) ; v . Add ( 0 ) ; v . Add ( - 1 ) ; queries . Add ( v ) ; v1 . Add ( 4 ) ; v1 . Add ( - 11 ) ; queries . Add ( v1 ) ; countShift ( arr , N , queries ) ; } }