You are on page 1of 1

C language: Sorting

Text: Chapter 8 & 9 of Algorithms in C (R. Sedgewick)


We shall continue practicing the C language with problems of sorting a collection of items.

Sorting is a general problem that occurs as a sub-problem of a wide variety of problems. It is not a hard
problem to solve however as Computer Scientists we are concerned mostly with developing efficient
algorithms for sorting, and implementing them. We are going to implement a program that sorts a
collection of numbers.

Assignment IV: Insertion Sort


In this assignment you will implement the insertion sort algorithm to order a collection of numbers.

Insertion sort is one of a number of established sorting algorithms. It is reasonably fast for small amounts
of input, and fairly easy to implement.

How Insertion Sort Works


Consider a list (or array) of n items. We want to re-arrange the items so that they are in ascending order
of size (or some other sorting criterion). Insertion works as follows:

We divide the collection into two parts or lists, one of which is already sorted, while the other is yet to be
sorted. Initially of course the first list is of size zero, since no items are yet sorted.

Our sorting strategy then ‘grows’ the sorted list, by taking an item out of the unsorted list and placing it
into the sorted list at the right place. At each step, the sorted list grows by one item, while the unsorted
list shrinks by one item. After n iterations of this, the sorting is complete! This is insertion sort.

How to do it
In this assignment, write a short program that reads in a sequence of numbers in arbitrary order from the
standard input. Store these numbers in an array. Write a function called insertion_sort(), which
takes the array as its first argument, the number of items in the array as its second argument, and
performs insertion sort on the array. Finally print out the result.

Using the ideas above, consider your array to be the list of items to be sorted. Conceptually split the array
into two parts using an index variable, where the part to the left of that variable is already sorted, while
the rest is not. You grow the sorted part by taking the item pointed to by the index and finding where to
place it in the part of the array to the left of the index variable. You may have to swap some array elements
to do this. Another possibility of course is that the item being considered stays right where it is (how?).
Increment your index variable to indicate the growth of your sorted list.

We can talk about this idea a little more in the lecture.

This assignment is due 2 weeks from the 10th of May 2021.

You might also like