Overview

  • Fixed size
  • Contiguous block of memory

Advantages

  • Constant index times

Disadvantages

  • Slow searching
  • Fixed size.  Changes in size are often costly in space and time.

Operations

Resizing

We need to resize arrays when we run out of room and want to insert more data. To resize, we allocate a new array with additional memory and copy over the entries from the original array.

Deleting

Deleting an item in an array requires moving all successive elements one over to the left to fill the vacated space.

The time complexity to delete the element at index i from an array of length n is O(n- i).

Time Complexities

OperationsAverage CaseWorst Case
IndexingO(1)O(1)
SearchingO(n)O(n)
InsertingN/AN/A

C# Syntax

Array Initialization Methods

new int[3]
new int[3] { 10, 20, 30 }
new int[] { 10, 20, 30 }
new[] { 10, 20, 30 }

You cannot do assignment or any mutation operations in a foreach loop.

Multidimensional Arrays

Tip – avoid using x and y as variable names. Instead use row and column.

Fixed length or symmetrical

C# Multidimensional Array Initialization

// creates a two-dimensional array of 
// four rows and two columns.
int[, ] twoDimArray = new int[4, 2];

//creates an array of three dimensions, 4, 2, and 3
int[,, ] threeDimArray = new int[4, 2, 3];

Jagged

An array whose elements are arrays is known as Jagged arrays it means “array of arrays“. The jagged array elements may be of different dimensions and sizes.

        /*----------2D Array---------------*/
        // Declare the array of two elements: 
        int[][] arr = new int[2][]; 
  
        // Initialize the elements: 
        arr[0] = new int[5] { 1, 3, 5, 7, 9 }; 
        arr[1] = new int[4] { 2, 4, 6, 8 }; 
  
        // Another way of Declare and 
        // Initialize of elements 
        int[][] arr1 = { new int[] { 1, 3, 5, 7, 9 }, 
                         new int[] { 2, 4, 6, 8 } };