First of all the definitive selection-sort:
for i in range(1, n - 1): exchange(t[i], t[rgmin (t, i, n)])
really i cant imagine, why anyone could use library sorting algorithm for testing. everybody could write this one-liner and actually
know the behaviour.
but this little blog-entry is about generic programming. first of all the motivation: i think, that it is something important to learn, to forget about certain things when programming. this is most of all storage! every assignment should be a pain in your heart, because you have to think about something for
nothing. so don't think about it while working on clever solutions.
Item max(Item a, Item b) { return (compare(a, b))? a : b; }
This is the max-algorithm. And works fine in c for every type of data. why? because we don't tell you anything about the data-type, it's just: Item.
Okay someday you have to write a cool solution for the item type, because it's c and c let's you do everything.
typedef char* Item;
This is the definition to import for the use of strings. Another thing to do is to tell the machine about
compare()
. we cant compare strings like integers or floats or whatever you want to use. but silly me i've already wrote in my first course about c every compare operation i could imagine, so i wrap it for strings about
strcmp()
bool compare(Item a, Item b){ return (strcmp(a, b) > 0); }
hmmm... ok i hate
string.h
and for real application i would not recommend it just for the sake of my paranoia. if i cant control my applications...
okay, and now you can use your smart algorithm for strings, and to change it for integers you just change
typedef int Item;
and here we go. you'll need another procedure to compare:
bool compare(Item a, Item b){ return (a > b); }
and compile.
for the full code examples use
this.
but why all this crazy effort? why not hard code everything? because you are lazy. me i always let have some crazy seconds where i type in items and procedures to call... and then i reuse it and reuse it and...
this is crazy, sexy, cool.
No comments:
Post a Comment