samedi 24 août 2019

Next_Permutation algorithm

I am trying to write algorithm for next permutation of given array of integers.My code is working for only some examples.So could anyone find where I am wrong?

The expected output differs from input only for the last three elements.So I checked the implementation of algorithm for last three elements.

   void Solution::nextPermutation(vector<int> &A) {


   int j,i;
    for(i=A.size()-1;i>0;i--){//loop to find i such that A[i-1]<A[i];

        if(A[i-1]<A[i]){j=i;break;}

    }
    if(i==0){sort(A.begin(),A.end());}
     /*to give the lowest order if  next_permutation 
    is not possible*/


    if(i>0){//if next permutation is possible


   //   to swap last element and element at j-1 th index

     swap(A[j-1],A[A.size()-1]);



     //to sort the elements after j-1 th index
       sort(A.begin()+j,A.end());


         }

Input [444, 994, 508, 72, 125, 299, 181, 238, 354, 223, 691, 249, 838, 890, 758, 675, 424, 199, 201, 788, 609, 582, 979, 259, 901, 371, 766, 759, 983, 728, 220, 16, 158, 822, 515, 488, 846, 321, 908, 469, 84, 460, 961, 285, 417, 142, 952, 626, 916, 247, 116, 975, 202, 734, 128, 312, 499, 274, 213, 208, 472, 265, 315, 335, 205, 784, 708, 681, 160, 448, 365, 165, 190, 693, 606, 226, 351, 241, 526, 311, 164, 98, 422, 363, 103, 747, 507, 669, 153, 856, 701, 319, 695, 52 ]

actual output [444 994 508 72 125 299 181 238 354 223 691 249 838 890 758 675 424 199 201 788 609 582 979 259 901 371 766 759 983 728 220 16 158 822 515 488 846 321 908 469 84 460 961 285 417 142 952 626 916 247 116 975 202 734 128 312 499 274 213 208 472 265 315 335 205 784 708 681 160 448 365 165 190 693 606 226 351 241 526 311 164 98 422 363 103 747 507 669 153 856 701 52 319 695 ]

expected output [444 994 508 72 125 299 181 238 354 223 691 249 838 890 758 675 424 199 201 788 609 582 979 259 901 371 766 759 983 728 220 16 158 822 515 488 846 321 908 469 84 460 961 285 417 142 952 626 916 247 116 975 202 734 128 312 499 274 213 208 472 265 315 335 205 784 708 681 160 448 365 165 190 693 606 226 351 241 526 311 164 98 422 363 103 747 507 669 153 856 701 695 52 319]

Aucun commentaire:

Enregistrer un commentaire