Understanding arrays

concept

An array, like a linked list, is a linear data structure.

advantages

Easy access to data

disadvantages

Adding and deleting data takes time

The characteristics of

  • Array form

As shown, a is the name of the array, and the number in [] indicates the number of digits in the array (array subscript).

  • Storage of arrays in memory

As shown in the figure, the data is stored sequentially in a contiguous space of memory.

Array access

Since the data is stored in contiguous space, the memory address of each data can be calculated using the array subscript, which allows direct access to the target data (random access).

For example, if we want to access Red, we can only look it up from scratch with a pointer, but in an array, we can access it directly by specifying the subscript in the array Red is in.

Increment of array elements

Adding data to any location in the array requires adding new storage space at the end of the array. To make room for the new data, the existing data is removed one by one, and the new data is finally written into the empty space where the element is to be added.

For example, you want to insert the Green element between Blue and Yellow. As is shown in

Adds new storage space at the end of the array

Move the Red element behind the new storage space

Move the Yellow element behind the new storage space

Insert Green into the new storage space

Delete an array element

To delete data anywhere in the array, you need to delete the target data first, then move the subsequent data one by one to the empty space, and finally delete the excess space.

For example, you want to delete the Green element.

Delete target data

I’m going to move Yellow to the empty space

Move Red to the empty space

Cut out the excess

Write in the last

  • The pictures used in this article are from “my first algorithm book”, if infringement, please leave a message in the comment section, the author immediately delete the relevant pictures.
  • If there are any errors in this article, please correct them in the comments section. If this article helped you, please like it and follow 😊
  • This article was first published in nuggets. Reprint is prohibited without permission 💌