#include #include using namespace std; int sortstring(string *a,int n) { for(int i=0;i<n-1;i++) { for(int j=0;j<n-1-i;j++) { if(a[j]>a[j+1]) { swap(a[j],a[j+1]); } } int size=min(a[i].length(),a[i+1].length()); for(int k=0;k<size;k++) { if(a[i][k]==a[i+1][k]) { if(k==size-1) { // cout<<"–"<<a[i].length()<<"–"<<a[i+1].length()<<"–"; if(a[i].length()<a[i+1].length()) { cout<<""<<a[i]<<""; swap(a[i],a[i+1]); cout<<"–"<<a[i]<<"–"; break; } } } } } return 0; } int main() { int n; cin>>n; string a[100]; for(int i=0;i<n;i++) { cin>>a[i]; } for(int i=0;i<n;i++) { cout<<a[i]<<endl; } sortstring(a, n); for(int i=0;i<n;i++) { cout<<a[i]<<endl; } return 0; }
Why doesnt my code sort bat and batman correctly?
Hey,
this is a utility of customised sort function
basically in the sort function you compare a+b with b+a
return the lexogrpahically smaller string.
This is an optimized version.
Hope it helps
Thats a different soution. I just want to know what is wrong with my code
This line is the problem,
basically is bat and batman is being compared.
A[i] = bat A[i+1] = batman
A[i].size() < A[i+1].size() then we are not required to swap …
so the condition has to be
if(a[i].length() > a[i+1].length()) then swap