 String Sort Problem

Only 1 test case is not running. I don’t what’s the error.

My approach for this problem is:

1. I have sort the array of strings simply using sort stl 1st.

2. Then after sorting I am running loop from n-1 to 1 if the first alphabet is same then simply check that A[i]>A[i-1] and if yess than swap them. For e.g:

if we simply sort the given test case then output will be :

apple

bat

batman

so according to my approach after sorting batman>bat hence I swap these two same upto 1.

But one test case is wrong. Please corresct me where I am wrong.

PS. If there is any other way also to solve this please let me know.

hi @rahul_bansal
refer this -->

#include <iostream>
#include <algorithm>
using namespace std;

int compareTo(string s1, string s2) {

int i = 0;

while (i < s1.length() && i < s2.length()) {

if (s1[i] > s2[i]) {

return 1;
} else if (s1[i] < s2[i]) {
return -1;
}
i++;

}

if (s1.length() > s2.length()) {
return -1;
} else {
return 1;
}

}
void sortfunc(string arr[], int n) {

for (int i = 0; i < n; i++) {

for (int j = 0; j < n - i - 1; j++) {

if (compareTo(arr[j], arr[j + 1]) > 0) {

string temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}

}
}

}

int main()
{

int n;
cin>>n;
string* str = new string[n];
cin.ignore();
for(int i=0;i<n;i++)
{
cin>>str[i];
}
sortfunc(str, n);
for(int i=0;i<n;i++)
{
cout<<str[i]<<endl;
}
}

Can U please explain the logic of CompareTo function

hi @rahul_bansal
that’s the main comparator function… try to dry run on a sample input… u will get better insight…

@Vaibhav277 I had dry run this but still not able to configured where I am wrong as I have also done the same thing so what’s the error in my code or please give me any exemplar test case where my code is failing.

hi @rahul_bansal
consider the input–>

3
ab
ac

expected o/p–>

ab
ac

ur o/p–>

ab
ac

@Vaibhav277 if we do this question by the following way then?

hi @rahul_bansal
U can’t simply check the first character and decide… it will give wrong ans… refer the code I sent u above…