2

Suppose I have the following values:-

xyz12@abc
xyz1@abc
xyz15@abc
xyz2@abc
xyz22@abc

I want the sorted output to be in form:-

xyz1@abc
xyz2@abc
xyz12@abc
xyz15@abc
xyz22@abc

If I use strcmp, then it will compare by each character and will give xyz1@ > xyz12 as @ > 2 which I don't want. What different algorithms can I use to sort this in the required format??

7
  • 5
    The Google keyword you're looking for is "natural sort". Commented Apr 9, 2012 at 20:21
  • 2
    You are confusing sorting algorithm and comparation criterium Commented Apr 9, 2012 at 20:23
  • Presumably, given extra rows [email protected] and [email protected], the results should list both those before the xyz* names, but [email protected] should be listed before [email protected] because 91 comes before 190 numerically. It is as yet undefined whether XYZ7@ABC should come before, after or in the midst of the original entries. Commented Apr 9, 2012 at 20:23
  • Treat each character as indicie in a base256 number system and using each characters ascii value apply your favorite sorting algorithm. Commented Apr 9, 2012 at 20:25
  • You can use any sort, just write your own compare function, that compares characters only up to @. Commented Apr 9, 2012 at 20:26

4 Answers 4

3

The Google keyword you're looking for is "natural sort".

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

1 Comment

Absolutely fantastic, specially the codinghorror article I read about natural sort. Three cheers Oli.
0

Look at how the sort utility is implemented:

$ cat test.txt | sort
xyz12@abc
xyz15@abc
xyz1@abc
xyz22@abc
xyz2@abc

Now with -V switch...

$ cat test.txt | sort -V
xyz1@abc
xyz2@abc
xyz12@abc
xyz15@abc
xyz22@abc

http://git.savannah.gnu.org/cgit/coreutils.git/tree/src/sort.c

Comments

0

if XYZ is alway the same, than use Counting sort on the integer value. Otherwise it is probably the easiest way to use some generic comparison based sort with custom comparator (i.e. Merge sort).

By generic I mean to use some preprogrammed sorting algorithm, which is prepared to accept some comparator function (returns typically 1 if A > B, -1 if A < B, 0 otherwise)

Comments

-1

I strongly suggest you to take a look at this website:

http://www.c.happycodings.com/Sorting_Searching/index.html

There you have a branch of sorting algorithms in C. Obviously take those whose performance is better (nlogn).

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.