Naim_Hasan's blog

By Naim_Hasan, 2 weeks ago, In English,

I have an array of strings.

I have to sort them in descending order. If 2 string have same length then we don't change their order.

So i wrote this code [Function in line 13 do the works mentioned above]

But for this given case below

17

sj a sa df r e w f d s a v c x z sd fd

Output: fd sa df sd sj d z x c v a s f w e r a

Right Output: sj sa df sd fd a r e w f d s a v c x z

[Problem is causing when 2 string have same length. Then those are automatically sorted lexicographic way. How to prevent it?]

[If i replace return a.length() > b.length();

in line 15 with return a.length() >= b.length();

then the code is crashed]

 
 
 
 
  • Vote: I like it
  • +11
  • Vote: I do not like it

»
2 weeks ago, # |
Rev. 4   Vote: I like it +8 Vote: I do not like it

Take a 2D vector of string . then push back elemnts as size . now start printing from then desending order as size .

vector<string> s[MAX_LENGTH] ;
long long mx=0 ,x;
for(int i=0;i<n;i++){
    string st ;
    cin >> st ;
    x=st.size() ;
    v[x].push_back(st) ;
    x=st.size() ;
    mx= max(mx,x) ;
}

for(int i=mx;i>=0;i--){
   for(auto it:s[i])
     cout << it << ' ' ;
}


»
2 weeks ago, # |
Rev. 3   Vote: I like it +8 Vote: I do not like it

Use stable sort instead of normal sort function.

Code

Cheers :)