Sorting, Searching and String Matching in C: From the Idea to a Program That Runs
It is the written test for Assistant Programmer. Question 6 carries ten marks: Write a C program to sort numbers from smallest to largest using bubble sort. You know bubble sort, and you can run it by hand on paper without a slip. Now the pen is in your hand and there is no compiler in the hall. Is the inner loop j < n - 1 or j < n - pass? Does the swap need < or <=? One wrong character, and the program that looked perfect on the page crashes, or runs forever, or does the worst thing a program can do: it prints a correct answer on your test data and is wrong anyway.
In the last chapter you traced algorithms by hand, with a table that has one column per variable. Here the computer makes that table for you. We will write each program, compile it with gcc, run it, and read the printout pass by pass. That printout is exactly the trace an examiner wants in your answer script, and it is also the quickest way to find out what a wrong line really does.
By the end of the chapter you will be able to write bubble, selection, insertion, merge, quick and heap sort in C, and iterative and recursive binary search, in the form a marker likes to see. You will read a printout and say which pass produced it, and count comparisons and swaps from the code. You will recognise the classic mistakes (the off-by-one loop bound, low < high, the empty-array crash, the unsigned counter, the negative remainder) and say what each one does. And you will write the string matchers, naive, KMP, Rabin-Karp and Boyer-Moore, as programs, not only as ideas.