Array Data Structure

An array consists of a sequence of similar data items that are stored sequentially in RAM.

The below code snippet is a sample array with three integer values.

int[] samplearray =  {1, 6, 5};

Usually index of an array starts with Zero

We can access individual element from an array using the index

In Samplearray[0] we're accessing the 0th index which will return a integer value 1

In Samplearray[1] we're accessing the 1st index which will return a integer value 6

This can be visualize as box with three partition

boxWithThreePartition.png

We cannot add more numbers/ more partitions to this array .In order to understand why we need to understand how a particular data item is stored in memory.

Consider this below statement

int value =  5 ;

This value 5 will be stored in memory as 32 bits of binary digits as

00000000000000000000000000000101

Each 1 and 0 is a bit and 8 bits form a byte which is a small unit of data.

Consider memory as a long tape with compartments, where each compartment is represented by an unique address and can hold a byte of data.

In the case of an array of integers [1, 6, 5], the memory tape would look like this:

MemoryTape.png

To store arrays we need consecutive compartments. Since we know in advance the exact size and index of value in the array , this setup makes the array more efficient for accessing the value through indexing.

But it makes it impossible to modify the size of the array.The memory which is allocated to it cannot be increased or decreased.

MultiDimensional array

Arrays can have more than one dimension. int[,] array = new int[3, 2];

This two dimensional array is organized as matrices which are the collection of 3 rows and 2 columns.

int[,] TwoDarray = new int[3, 2] {{1,2} ,{3,4} , {5,6} }

The matrix representation of the above TwoDarray array is

Matrix.PNG

Although 2D arrays exist from the user's perspective, the storage process for a 2D array is the same as for a one-dimensional array. A 2D array's size is equal to its rows and columns multiplied.

The difference between the orders lies in which elements of an array are contiguous in memory. In row-major order, the consecutive elements of a row reside next to each other, whereas the same holds true for consecutive elements of a column in column-major order.

RowMajorVsColumnMajor.png By Cmglee - Own work, CC BY-SA 4.0, commons.wikimedia.org/w/index.php?curid=651..

Here's a summary of the Big O of common array methods:

ArrayBigONotation.PNG