Naim_Hasan's blog

By Naim_Hasan, 2 weeks ago, ,

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]

• +11

 » 2 weeks ago, # | ← Rev. 4 →   +8 Take a 2D vector of string . then push back elemnts as size . now start printing from then desending order as size . vector s[MAX_LENGTH] ; long long mx=0 ,x; for(int i=0;i> 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, # ^ |   +3 Wow, that was a pretty interesting idea.
 » 2 weeks ago, # | ← Rev. 3 →   +8 Use stable sort instead of normal sort function. Code#include using namespace std; bool comp(string a,string b){ if(a.size() > b.size())return true; return false; } int main(){ int n;cin>>n; string a[n]; for(int i=0;i>a[i]; stable_sort(a,a+n,comp); for(int i=0;i
•  » » 2 weeks ago, # ^ |   +3 That was interesting. Thanks for your time.