Thinking in C and *nix (CSC 282 2015S) : EBoards
Primary: [Front Door] [Schedule] - [Academic Honesty] [Disabilities] [Email] [FAQ] [Teaching & Learning] - [Calendar]
Current: [Outline] [EBoard] [Lab] [Assignment]
Sections: [Assignments] [EBoards] [Examples] [Handouts] [Labs] [Outlines]
Reference: [EBook] - [ISO] [GNU Coding Standards] [GCC Documentation] - [TAoUP] [Make3]
Previous Offerings: [CSC 295 2013S] [CSC 295 2014S]
Misc: [SamR] [Glimmer Labs] [CS@Grinnell] [Grinnell] [Issue Tracker]
Overview
assert.In Scheme
;;; Procedure:
;;; sort
;;; Parameters:
;;; lst, a list (or perhaps vec, a vector)
;;; order, a two-parameter predicate that represents
;;; a total order. ("Does a come before b?")
In Java, we also think about providing a Comparator (or using Comparables)
What about C? What's your signature for a procedure that sorts an array of strings?
Question: Do we sort "in place" or do we return a sorted array?
/**
* Sort strings. Return 1 upon success and 0 upon failure.
*/
int
sort (char *strings[], int len)
{
} // sort
Can we make this take a comparator?
/**
* Sort strings. Return 1 upon success and 0 upon failure.
*/
int
sort (char *strings[], int len, int (*compare)(char *x, char *y))
{
} // sort
This says "compare is a function that takes two strings as input and returns an integer."
Many novice C programmers find this hard to read. Sometimes typedefs are useful.
/**
* Functions that return negative if x comes before y, 0 if
* x "equals" y, and pos if x is greater than y.
*/
typedef int (*Comparator)(char *x, char *y);
int
sort (char *strings[], int len, Comparator compare)
{
} // sort
How do we call sort?
int
compare_by_length (char *x, char *y)
{
return strlen (x) - strlen (y);
} // compare_by_length
sort (strings, adfas, compare_by_length);
assert