1

Is it possible to merge sort an array of strings? For example if I have an array of strings in C like...

arr[0]="Hello";
arr[1]="cat";
arr[2]="there";
arr[3]="apple";
arr[4]="flower";

The sorted output should be...

apple
cat 
flower
hello
there

Also I don't understand what I should do if I have 2 words like "Hello" and "Hell?" Everywhere the examples are always for integers and never strings especially in C++.

6
  • (1) Yes, it's possible to merge sort an array of strings, (2) make sure that your compare function handles the case "Hello"/"Hell" appropriately (usually that means that "Hell" < "Hello"). Commented Oct 4, 2013 at 23:12
  • So for Hall and Hell is Hall>Hell? Commented Oct 4, 2013 at 23:15
  • What? Certainly not. Maybe we disagree about the < sign. By Hell < Hello I mean that Hell would go before Hello. I certainly hope you're not asking whether Hell should be before Hall alphabetically.... Commented Oct 4, 2013 at 23:17
  • Sorry, but I was wondering about 2 strings like Hall and Hell.! Commented Oct 4, 2013 at 23:22
  • std::sort()? Commented Oct 4, 2013 at 23:25

1 Answer 1

1

Yes, in your comparision, use strcmp for C, and std::string::compare for C++. Both functions will compare the strings, and return an integer with the following meanings...

  • < 0   —   Either the value of the first character that does not match is lower in the compared string, or all compared characters match but the compared string is shorter.

  • = 0   —   They compare equal

  • > 0   —   Either the value of the first character that does not match is greater in the compared string, or all compared characters match but the compared string is longer.

This will also take into account "Hello" vs. "Hell" and will will subsequently sort "Hell" before "Hello".

Note: If you find that you are like me, and have a hard time remembering what the result means. Simply put the comparison operator (as in the example above) inbetween str1 and str2. So, for example, if you called strcmp(str1, str2) and the result was < 0, then look at it like str1 < str2.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.