Hey guys just wondering if u know how to sort an array of strings without using qsort and all of those. I dont get how all the swapping works and so on?
Hey guys just wondering if u know how to sort an array of strings without using qsort and all of those. I dont get how all the swapping works and so on?
All I can think of is to parse the strings until the null character is reached. That is, check to see if the given character has a value of 0. Once reached, use temporary strings (locally-defined would be one method) to store the contents. When done, write the strings in the order as you want. It's one method, but probably a lousy one.
High elevation is the best elevation. The higher, the better the view!
My computer: XP Pro SP3, 3.4 GHz i7-2600K CPU (OC'd to 4 GHz), 4 GB DDR3 RAM, X-Fi Platinum sound, GeForce 460, 1920x1440 resolution, 1250 GB HDD space, Visual C++ 2008 Express
to compare strings - use strcmp
to swap strings - strcpy (or if you can mange to build array of pointers to strings - just swap pointers)
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler
This is sample code snap which is used for sorting the array. Well, it just the compare and copy part of the whole sorting code. You should try using this code to build your whole sorting program.
ssharish2005Code:if( strcmp(str[i], str[j]) > 0) { strcpy(temp,str[i]); strcpy(str[i],str[j]); strcpy(str[j],temp); }
As vart was saying, if you pointers to strings (for example if the strings were dynamically allocated), you can just swap pointers.
Also see these pages for actual sorting algorithms.Code:char *p; if(strcmp(str[i], str[j]) > 0) { p = str[i]; str[i] = str[j]; str[j] = p; }
http://cprogramming.com/tutorial.html#algorithms
http://en.wikipedia.org/wiki/Sorting_algorithm
http://en.wikipedia.org/wiki/Category:Sort_algorithms
dwk
Seek and ye shall find. quaere et invenies.
"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell
Other boards: DaniWeb, TPS
Unofficial Wiki FAQ: cpwiki.sf.net
My website: http://dwks.theprogrammingsite.com/
Projects: codeform, xuni, atlantis, nort, etc.