Sort with a comparator
Sort an array into an order defined by a callback. A medium embedded C problem (Function pointers and state machines), run and graded in the browser.
medium · Function pointers and state machines · callbacks · sorting
Sort the n values at a in place. The callback before(x, y) returns true when x must come before y.
After sorting, no element may need to come before the element in front of it. Small arrays are the norm on an MCU, so a simple insertion sort is appropriate.
Starter code
void sort_by(int16_t *a, size_t n, bool (*before)(int16_t, int16_t)) {
// Order the array so that before(a[i + 1], a[i]) is never true.
}Example tests
Ascending
int16_t a[] = { 5, -1, 3, 0 };
sort_by(a, 4, ascending);
printf("%d %d %d %d\n", a[0], a[1], a[2], a[3]);Expected output:
-1 0 3 5Descending
int16_t a[] = { 5, -1, 3, 0 };
sort_by(a, 4, descending);
printf("%d %d %d %d\n", a[0], a[1], a[2], a[3]);Expected output:
5 3 0 -1Learn it first
- Function pointers and callbacks · Callbacks, dispatch tables and the context pointer that makes them reusable.
More Function pointers and state machines problems
- Dispatch through a vector table · Call the handler registered for an interrupt number, with a safe fallback.
- Replace a switch with a table · Select an operation by opcode using an array of function pointers.
- Apply a function to a buffer · Transform every element of an array with a caller-supplied function.
- Command table lookup · Find a command by name in a table and call its handler.
- State transition function · Implement the transition rules of a motor controller.
- Publish and subscribe · Keep a fixed-size list of callbacks and notify them in order.
- Callback with context · Invoke a callback for every set bit, passing through a user context.
- Generic minimum · Find the smallest element of an array of any type using a comparator.
- State handlers · Build a state machine in which each state is a function.
- TV remote: a table of key actions · Look a key code up in a table and call its action with the device's context.