Queries to find minimum swaps required to sort given array with updates | 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 ; Given array arr [ ] ; Given Queries ; Function Call
function computePos ( arr , n , value ) { if ( value < arr [ 0 ] ) return 0 ; if ( value > arr [ n - 1 ] ) return n - 1 ; var start = 0 ; var end = n - 1 ; while ( start < end ) { var mid = parseInt ( ( start + end + 1 ) / 2 ) ; if ( arr [ mid ] >= value ) end = mid - 1 ; else start = mid ; } return start ; } function countShift ( arr , n , queries ) { for ( var i = 0 ; i < queries . length ; i ++ ) { var index = queries [ i ] [ 0 ] ; var update = queries [ i ] [ 1 ] ; var newElement = arr [ index ] + update ; var newIndex = computePos ( arr , n , newElement ) ; document . write ( Math . abs ( newIndex - index ) + " " ) ; } } var arr = [ 2 , 3 , 4 , 5 , 6 ] ; var N = arr . length ; var queries = [ [ 0 , - 1 ] , [ 4 , - 11 ] ] ; countShift ( arr , N , queries ) ;