Programming by Example

A BB4W Compendium

Linked List & Sorting

Solid 3D objects need to be sorted by distance before drawing, otherwise the illusion of depth can be destroyed. However, sorting takes time.

One compromise solution involves the use of a linked list. A linked list is very similar to the design of this website, where each page has a link to the previous page and the next page. If we want to change the order in which the pages are presented (when using the arrow buttons) then instead of moving the contents of the page, we change the links that point to the page, and to the neighbouring pages.

Benefits of a linked list:

Increased speed of processing. A program may be required to handle large volumes of 3D objects at peak periods, but only small amounts on average. By using a linked list, we can reserve a very large array, but we only access/process the array rows that are currently in use.

A linked list can be sorted by changing the pointers of the relevant rows, removing the need to move the entire contents of individual rows.

All sorted?

This program uses the simplest method of sorting: effectively comparing two rows at a time and swapping their positions in the list, if necessary. However, we don't repeat the usual cycle i.e. processing until the array is perfectly sorted. Instead, we rely on the fact that objects won't change position radically and the list will be sorted gradually, one animation frame at a time. It's a never ending process and a compromise solution that works reasonably well.

This compromise solution can be enhanced because we are able to insert objects into the list at specific points e.g. when a diamond explodes, a number of tetrahedrons are inserted immediately after the diamond in the list (because they appear in the same region of space). This gives the process of sorting a head start.