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?
Printable View
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.
to compare strings - use strcmp
to swap strings - strcpy (or if you can mange to build array of pointers to strings - just swap pointers)
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