Can someone please explain where my code is going wrong for the following problem ?

Problem link : http://codeforces.com/contest/1256/problem/B

The question is to print the lexicographically smallest array by doing atmost n-1 consequtive swaps . Each pair i,i+1 must be swapped only once .

My code :

```
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while(t--)
{
int n;
cin >> n;
int a[n+1];
for(int i = 1 ; i <= n ; i++ ){
cin >> a[i];
}
int m = n-1,k=1,pos;
while(m>0)
{
for(int i = 1 ; i<=n ; i++ ){
if(a[i]==k){
pos = i;
break;
}
}
if(pos<k)
{
while(m>0 && pos!=k && pos<n){
swap(a[pos],a[pos+1]);
m--;
pos++;
}
}
else if(pos>k)
{
while(m>0 && pos!=k && pos>1){
swap(a[pos],a[pos-1]);
m--;
pos--;
}
}
k++;
if(k==n && a[n]==n){
break;
}
}
for(int i = 1 ; i<=n ; i++ ){
cout<<a[i]<<' ';
}
cout<<'\n';
}
}
```