Moved to Wordpress

This blog has moved to Wordpress. GOTO the new blog now.

There will be no new updates here. Most of the posts have also been expanded.

2010/08/31

What In The Hell Are Arrays

Arrays are one of the oldest and simplest data structures. An array is a collection of elements that can be accessed by an index. An array’s index usually starts at 0 and stops at the number of elements in the array minus 1. The diagram below shows an array of the characters in the string “HELLO”.



In the array above the ‘0’ element is the character “H”, the ‘1’ element is the character “E” and so on.

Arrays have constant time access to the elements stored within. This means that it takes the same amount of time to access any element. For example, it would take the same amount of time to access the last element of an array as it would the first, or even an element in the middle.

In lower level languages an array can only contain elements of a single type. This makes storing and retrieving elements in an array very easy. In an array of fixed sized elements the next element is simply the size of the individual elements away. For instance an array of integers, where the integers are 4 bytes long, would have the first element at address ‘0’, the second at address 4, the third at address 8 and so on. So when you want the element referenced by the index 3 you can just multiply 3 * 4 and get the address of the 3rd element.

Multi-Dimensional Array



A multi-dimensional array is simply an array of arrays. A spreadsheet is a form of multi-dimensional array. The diagram above shows a 3 element array where each element is also a 3 element array.

As mentioned above a multi-dimensional array can be useful in implementing a spreadsheet, where the first array is an array of rows and each element is an array of columns. They can be used for many things from tracking pieces in a chess game to drawing graphics on your screen and much more.



C

An array in C can contain elements of only one type/size and is not resizable.

Create an array:
int a[3] = {5, 10, 15};

Access an array element:
a[1] ==> 10

Python

An array in Python is called a list. It can contain elements of any type/size and is resizable.

Create an array:
a = [5, 10, 15]

Access an array element:
a[1] ==> 10

Scheme

An array in Scheme is called a vector. It can contain elements of any type/size and may be resizable.

Create an array:
(define a (vector 5 10 15))
(define b #(5 10 15))

Access an array element:
(vector-ref a 1) ==> 10

No comments:

Post a Comment