Array

0 phút đọc

Quick reference

Worst Case
space (O(n))
lookup (O(1))
append (O(1))
insert (O(n))
delete (O(n))

An array organizes items sequentially, one after another in memory.

Each position in the array has an index, starting at 0.

Strengths

  • Fast lookups. Retrieving the element at a given index takes (O(1)) time, regardless of the length of the array.
  • Fast appends. Adding a new element at the end of the array takes (O(1)) time, if the array has space.

Weaknesses

  • Fixed size. You need to specify how many elements you're going to store in your array ahead of time. (Unless you're using a fancy dynamic array.)
  • Costly inserts and deletes. You have to "scoot over" the other elements to fill in or close gaps, which takes worst-case (O(n)) time.

In Python 3.6

Some languages (including Python) don't have these bare-bones arrays.

Here's what arrays look like in Java.

// instantiate an array that holds 10 integers
int gasPrices[] = new int;

gasPrices = 346;
gasPrices[1] = 360;
gasPrices = 354;

Inserting

If we want to insert something into an array, first we have to make space by "scooting over" everything starting at the index we're inserting into:

Inserting into an array

In the worst case we're inserting into the 0th index in the array (prepending), so we have to "scoot over" everything in the array. That's (O(n)) time.

Deleting

Array elements are stored adjacent to each other. So when we remove an element, we have to fill in the gap—"scooting over" all the elements that were after it:

Deleting from an array

In the worst case we're deleting the 0th item in the array, so we have to "scoot over" everything else in the array. That's (O(n)) time.

Why not just leave the gap? Because the quick lookup power of arrays depends on everything being sequential and uninterrupted. This lets us predict exactly how far from the start of the array the 138th or 9,203rd item is. If there are gaps, we can no longer predict exactly where each array item will be.

Data structures built on arrays

Arrays are the building blocks for lots of other, more complex data structures.

This markdown conversion represents the structure and content of the provided HTML snippet. The conversion includes headings, lists, bold text, and mathematical notations using LaTeX. Links and images are also formatted using markdown syntax. Please note that the actual URLs for images and links are placeholders and should be replaced with the correct paths in your actual markdown file.

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào

Avatar TechMely Team
Được viết bởi

TechMely Team

Đôi khi, không cẩn thận biết một số chuyện, mới phát hiện ra rằng những điều bản thân để tâm lại nực cười đến thế.
Khoá học javascript từ cơ bản đến chuyên sâuYoutube Techmely