What is the best sorting algorithm I can implement in C?
Depends on the data and the use of the sort.
Bubble sort is the simplest one but is the most expensive one. Expense won't matter if data size is small.
I want something better than the default qsort() :-P
Heapsort is a good one that also has nLOG(n) sort time. But, heap may not be the best structure to organize your data. Again, depends on the problem.
For numbers like zip codes, you can use Radix sort. It is N*M time where M is the number of digits.
BTW - quicksort() is on average nLOG(n) time, but really depends on the pivot you choose. Terrible pivots can make the algorithm just as bad as Bubble Sort.
How about timsort?
It is newer (after my time), but appears like a good one for data with many sorted elements already. Again, I suggest you evaluate these in the context of the data you are dealing with and the structure that is best needed to represent the data.
I want to sort characters in strings, where each string is a single english word.
If the string length is constrained (not arbitrarily large), Radix sort might work better. Review that one and see.
I will restrict it to 4-10 letter english words
or maybe just 4 :-P
If you are doing it for programming practice, I then would encourage you to do as many ways as you can. Gives you good practice and insight into each algorithm.
will this work? char *sortedWord(const char *word, char *wbuf) { char *p1, *p2, *endwrd; char t; int swaps; strcpy(wbuf, word); endwrd = wbuf+strlen(wbuf); do { swaps = 0; p1 = wbuf; p2 = endwrd-1; while (p1<p2) { if (*p2 > *p1) { t = *p2; *p2 = *p1; *p1 = t; swaps = 1; } p1++; p2--; } p1 = wbuf; p2 = p1+1; while(p2 < endwrd) { if (*p2 > *p1) { t = *p2; *p2 = *p1; *p1 = t; swaps = 1; } p1++; p2++; } } while (swaps); return wbuf; }
ONLY COME WHEN THIS QUESTIONS HAS BEEN ANSWERED http://openstudy.com/?F486443823888OWAFDL=_#/updates/4ec93881e4b095539996a25a
Can you show an example with words so I understand what you are trying to achieve?
Join our real-time social learning platform and learn together with your friends!