排序前后的各相应位置上的值,挨着比较即可,每有一个不同的,答案就加一:

import java.util.*;
public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] v = new int[n], r = new int[n];
        for(int i = 0; i < n; ++i) v[i] = sc.nextInt();
        for(int i = 0; i < n; ++i) r[i] = v[i];
        Arrays.sort(r);
        int sum = 0;
        for(int i = 0; i < n; ++i){
            if(r[i] != v[i]) sum++;
        }
        System.out.println(sum);
    }
}