Updated chapter3.txt

TaylorH authored
revision 9a95e61682bef864c6dee90e78466a10ced7942b
section1/chapter3
# Arrays
I'm sure you've worked with arrays by now, and despite being a 'simple' data structure, they are still quite useful, and as such we should probably go over them from an algorithms

##Idea
The idea behind an array is that you take a chunk of memory of a predetermined size and fill it with data. Each item in the array can be directly referenced by it's index.

Some of the advantages of an array are:
- Pretty much every programming language has them built in and they are typically very easy to code.
- It's quick and easy to access any item within it, all you need to know is it's index, no traversal needed.
- It's quick and easy to add a new item to the end of it.

Some of the disadvantages of an array are:
- You typically have to declare the size of an array up front and cannot change that size. If you don't know how many items you're going to be working with, this can be problematic. Either you make the array too big and waste space, or too small and run out of room.
- Inserting items anywhere but the end of the array involves shifting every single item after it to the right by one. If you're working with a large amount of data, this can really add up.

##Implementation
Usually just something along the lines of:
`int myArray [size]` Where _int_ is the type of data and _size_ is how big you want the array to be.

##Variations
A _two-dimensional array_, where each item in an array is another array, forming what would look like a matrix with rows and colums.
In fact, you don't have two stop at two dimensional, you can theoretically go as deep as you'd like though it would get fairly complicated fairly quickly.

A _resizable array_ isn't really a variation so much as it is a way to get around the size limitation of an array. Basically whenever you reach the end of an array, you create a new array of twice the size and copy everything into the new array, and anytime you get down to less then a third of the array being full, create a new array of half the size and copy everything into it.
```
if (myArray.isFull() == true) {
int myNewArray[myArray.size * 2];
copy(myArray, myNewArray);
}
...
if (myArray.isTwoThirdsEmpty() == true) {
int myNewArray[myArray.size / 3];
copy(myArray, myNewArray);
}
```




##Analysis
Access - Since you can access any element directly by it's index, the access time can be said to be ~1 or O(1).
Insertion - In the worst case, you insert at the beginning of the array, it would involve shifting every existing element by one. If n = the length of the array, this would be ~n or O(n).
Removal - For the same reasons as insertsion. ~n or O(n).