lundi 15 février 2021

Please help me to optimize my Trouble sort problem code

can someone please help to optimize my code of trouble sort problem.

problem-> Given a list of N integers, determine whether Trouble Sort will successfully sort the list into non-decreasing order. If it will not, find the index (counting starting from 0) of the first sorting error after the algorithm has finished: that is, the first value that is larger than the value that comes directly after it when the algorithm is done.

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int test_case;
    cin>>test_case;
    for(int p=1;p<=test_case;p++)
    {
        int n,a[n];
        cin>>n;
        for(int i=0;i<n;i++)
        {
            cin>>a[i];
        }
        bool done=false;
        while(!done)
        {
            done=true;
            for(int i=0;i<n-2;i++)
            {
                if(a[i]>a[i+2]){
                    swap(a[i],a[i+2]);
                    done=false;
                }    
            }
        }
        int flag=-1;
        for(int i=0;i<n-1;i++)
        {
            if(a[i]>a[i+1])
            {
                flag=i;
                break;
            }
        }
        if(flag==-1)
            cout<<"Case #"<<p<<": OK\n";
        else
            cout<<"Case #"<<p<<": "<<flag<<endl;
    }
}

Aucun commentaire:

Enregistrer un commentaire