Saturday, August 10, 2013

Arrays

Code examples for this entry are located here - Arrays

Arrays are probably one of the most important yet basic data structures that we use. By definition, an array is a data structure that is used to represent a group of items that can be accessed by an index. In other words, we can imagine an array as the mailboxes along a street, where the number at the front of the mailbox represents the index and the street represents the size of the array.


Figure 1. An array represented as a group of mailboxes with index starting at 0

When we create an array, we usually give it a predefined size, which determines the maximum number of items we can store within it.

In programming languages such as Java and C, array indices always start from 0 rather than 1, which might cause some confusion initially. All this means is that to access the nth item in the array, we look for it in position n - 1.

Using our mailbox example and referring to Figure 1, the number of mailboxes is the size of our array, which in the above example is 4. The numbers on the mailbox themselves represent the array indices, which in this instance begins at 0 and goes to 3. This means that to get to the 2nd mailbox, we look for it at the n - 1 position, where n = 2. Subsequently to get to the 3rd mailbox, it is at position 2 and so forth.  

Continuing with our mailbox example, if we want to add or remove items from any mailbox, we access it by the same way in which we look for it. Once we have found it, we can easily add and remove items from our mailbox.