Count of elements which are not at the correct position | Java implementation of the approach ; 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
import java . util . * ; class GFG { static int cntElements ( int arr [ ] , int n ) { int copy_arr [ ] = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) copy_arr [ i ] = arr [ i ] ; int count = 0 ; Arrays . sort ( arr ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != copy_arr [ i ] ) { count ++ ; } } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 6 , 2 , 4 , 5 } ; int n = arr . length ; System . out . println ( cntElements ( arr , n ) ) ; } }