Count of elements which are not at the correct position | Function to return the count of elements which are not in the correct position when sorted ; To store a copy of the original array ; Copy the elements of the given array to the new array ; To store the required count ; Sort the original array ; If current element was not at the right position ; Driver code
function cntElements ( arr , n ) { let copy_arr = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) copy_arr [ i ] = arr [ i ] ; let count = 0 ; arr . sort ( ( a , b ) => a - b ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != copy_arr [ i ] ) { count ++ ; } } return count ; } let arr = [ 1 , 2 , 6 , 2 , 4 , 5 ] ; let n = arr . length ; document . write ( cntElements ( arr , n ) ) ;