------
## 最终结论
```python
def min_operations_to_sort(q, queries):
    results = []
    for i in range(q):
        n = queries[i][0]
        a = queries[i][1]

        # Calculate the frequency of each element
        freq = {}
        for num in a:
            if num in freq:
                freq[num] += 1
            else:
                freq[num] = 1

        # Calculate the longest sorted subsequence by checking the prefix length
        max_length = 0
        current_length = 0
        last_num = -1

        for num in sorted(freq.keys()):
            if num == last_num + 1:
                current_length += freq[num]
            else:
                current_length = freq[num]
            max_length = max(max_length, current_length)
            last_num = num

        # Minimum operations needed is to move all elements not in the longest sorted subsequence
        results.append(n - max_length)

    return results


# Read input
import sys
input = sys.stdin.read
data = input().split()

q = int(data[0])
index = 1
queries = []

for _ in range(q):
    n = int(data[index])
    a = list(map(int, data[index+1:index+1+n]))
    queries.append((n, a))
    index += n + 1

# Get results and print them
results = min_operations_to_sort(q, queries)
for result in results:
    print(result)
```