27
Arrays and linked lists
item #2. Then you have to go to item #2 to get the address for item #3.
And so on, until you get to the last item. Linked lists are great if you’re
going to read all the items one at a time: you can read one item, follow
the
address to the next item, and so on. But if you’re going to keep
jumping around, linked lists are terrible.
Arrays are different. You know the address for every item in your array.
For example, suppose your array contains five items, and you know it
starts at address 00. What is the address of item #5?
Simple math tells you: it’s 04. Arrays are
great if you want to read
random elements, because you can look up any element in your array
instantly.
With a linked list, the elements aren’t next to each other,
so you can’t instantly calculate the position of the fifth element in
memory—you have to go to the first element
to get the address to the
second element, then go to the second element to get the address of
the third element, and so on until you get to the fifth element.
Terminology
The elements in an array are numbered. This numbering starts from 0,
not 1. For example,
in this array, 20 is at position 1.
And 10 is at position 0. This usually throws new programmers for a
spin. Starting at 0 makes all kinds of array-based code easier to write,
so programmers have stuck with it.
Almost every programming
language you use will number array elements starting at 0. You’ll
soon get used to it.
28
The position of an element is called its
index.
So instead of saying, “20 is
at
position
1,”
the correct terminology is, “20 is at
index
1.” I’ll use
index
to mean
position
throughout this book.
Here are the run times for common operations on arrays and lists.
Question: Why does it take O(
n
) time to insert an element into an
array? Suppose you wanted to insert an element
at the beginning of an
array. How would you do it? How long would it take? Find the answers
to these questions in the next section!
Dostları ilə paylaş: