I want to create a program to generate the steps of swapping elements during changing an array to another array,(eg:from {0,1,2} to {0,2,1}, the step is 1<->2, which means swap the position of element 1 and element 2),taking A={0,1,3,2} and B={2,0,3,1} as example, my original concept is as following:
- get the steps of swapping elements during sorting A in asending order
- get the steps of swapping elements during sorting B in asending order
- swap the elements in A, starting from following the steps to sort A, then follow the steps to sort B but in reverse order
it is the code I tried:
#include <stdlib.h>
#include <functional>
#include <vector>
int main(){
std::function<bool(int,int)> f=[](int a,int b){
if(a>=b)
printf("%d<->%d\n",a,b);
return a<b;
};
std::vector<int> a={0,1,3,2};
std::sort(a.begin(),a.end(),f);
printf("---\n");
std::vector<int> b={2,0,3,1};
std::sort(b.begin(),b.end(),f);
return 0;
}
output:
1<->0 //step to sort A
3<->1
2<->1
---
3<->0 //step to sort B
3<->2
1<->0
so the step to change from 0,1,3,2 to 2,0,3,1 should be:
1<->0
3<->1
2<->1
1<->0
3<->2
3<->0
but when I follow the step:
0,1,3,2
1,0,3,2
3,0,1,2
3,0,2,1
3,1,2,0
2,1,3,0
2,1,0,3
the result is 2,1,0,3 instead of 2,0,3,1, why? Is my concept to generate the step wrong? if so, is there other way to generate the step to change an array to another array by swapping position?