Will anyone help me with this problem I am getting TLE in this problem.
Problem
Given an integer array of length n and q queries.
Each query has a form a b, where a and b are numbers of elements in the array to be swapped. Your task is to tell after each query if the array is sorted by non-decreasing order.
Input format
The first line of the input contains two integers n and q (2≤n≤2⋅10^5, 1≤q≤10^5) — length of the given array and number of the queries respectively.
The second line contains n positive integers, does not exceed 10^9 — initial values of the array elements.
Then q lines follow, each containing two distinct integers a and b (1≤a,b≤n) — indices of elements to be swapped at the current query.
Output format
For each query, print in the new line “Sorted!” if the array is sorted in non-decreasing order after that query, or “Unsorted!” otherwise.
Sample 1
Input
5 4
1 2 5 3 4
3 4
4 5
1 5
5 1
Output
Unsorted!
Sorted!
Unsorted!
Sorted!
Sample 2
Input
2 3
2 10
1 2
1 2
1 2
Output
Unsorted!
Sorted!
Unsorted!
My Solution:
#include <bits/stdc++.h>
using namespace std;
#define FORN(i, a, b) for (int i = (a); i < (b); i++)
bool arraySortedOrNot(int a[], int n)
{
if (n == 1 || n == 0)
{
return true;
}
return a[n - 1] >= a[n - 2] &&
arraySortedOrNot(a, n - 1);
}
void solve();
int main(){
cin.tie(0);
cout.tie(0);
solve();
return 0;
}
// Write CODE here without Test case---#
void solve(){
int n,q;
scanf("%d %d",&n,&q);
int arr[n];
FORN(i,0,n)scanf("%d",&arr[i]);
FORN(i,0,q){
int a,b;
scanf("%d %d",&a,&b);
swap(arr[a-1],arr[b-1]);
if(arraySortedOrNot(arr,n)) {printf("Sorted!\n");}
else {printf("Unsorted!\n");}
}
}