Understanding Data Structures and Algorithms: Arrays
Collins Oden

Understanding Data Structures and Algorithms: Arrays

What is an array?

An array is a type of data structure which consists of a collection of elements, values or variables each identified by an index or key.

Look at the following code snippets:


No alt text provided for this image
Using named variables for naming data
No alt text provided for this image
Storing data in an array

From the two code snippets above, both print numbers from 1 to 4. The first began by creating each variable to hold each number, the second implemented array which holds all numbers which can each be accessed with their indexes.

This might not look so much of a problem until you begin having numbers spanning to millions and billions, your code becomes complex and bulky if you are to create every variable to hold a number. You will also spend a lot of time trying to access each data stored in each variable.

Array helps to gather data with a single identifier name. Each value in an array is regarded as a member of that array.

Arrays can be initialized differently in different languages as seen in the image below:

# Initializing array in C+
int numbers[] = { 1, 2, 3, 4 };


# Initializing array in C#
int[] numbers = { 1, 2, 3, 4 };


# Initializing array in Java
int[] numbers = { 1, 2, 3, 4 };


# Initializing array in Python
numbers = [ 1, 2, 3, 4 ]


# Initializing array in PHP
$numbers = array(1, 2, 3, 4);
        

When an array is created, it is stored in memory as shown below:

No alt text provided for this image
Array in memory


To get the value 2, you must know which index holds the number ‘2’. So, 2 can be accessed using numbers[1] since it is located in index 1. The size or length of an array implies the number of members an array has. Most languages do not supports expansion of the size of an array, once an array is initialized, the initial length is taken and there is usually no room for expansion.

Arrays can store one sequence of data (i.e list of data) either in a column or row, this is is called multi-dimentional array and an array can also store lists of lists (like a table with multiple rows and columns containing data).

Arrays helps to speadily access elements. Also, because an array is stored in a single variable, memory is conserved as creating more variables with different names consumes memory.


...to be continued

要查看或添加评论,请登录

Collins Oden的更多文章

社区洞察

其他会员也浏览了