A Dynamic array (vector in C++, ArrayList in Java) automatically grows when we try to make an insertion and there is no more space left for the new item. Usually the area doubles in size. A simple dynamic array can be constructed by allocating an array of fixed-size, typically larger than the number of elements immediately required. The elements of the dynamic array are stored contiguously at the start of the underlying array, and the remaining positions towards the end of the underlying array are reserved, or unused. Elements can be added at the end of a dynamic array in constant time by using the reserved space until this space is completely consumed. When all space is consumed, and an additional element is to be added, the underlying fixed-sized array needs to be increased in size. Typically resizing is expensive because you have to allocate a bigger array and copy over all of the elements from the array you have overgrow before we can finally append our item.Â
Approach: When we enter an element in array but array is full then you create a function, this function creates a new array double size or as you wish and copy all element from the previous array to a new array and return this new array. Also, we can reduce the size of the array. and add an element at a given position, remove the element at the end default and at the position also.
Key Features of Dynamic Array
Add Element: Add element at the end if the array size is not enough then extend the size of the array and add an element at the end of the original array as well as given index. Doing all that copying takes O(n) time, where n is the number of elements in our array. That’s an expensive cost for an append. In a fixed-length array, appends only take O(1) time. But appends take O(n) time only when we insert into a full array. And that is pretty rare, especially if we double the size of the array every time we run out of space. So in most cases appending is still O(1) time, and sometimes it’s O(n) time. In dynamic array you can create fixed-size array when required added some more element in array then use this approach:
Delete Element: Delete an element from array, default remove() method delete an element from end, simply store zero at last index and you also delete element at specific index by calling removeAt(i) method where i is index. removeAt(i) method shift all right element in the left side from the given index.
Resize of Array Size: When the array has null/zero data (aside from an element added by you) at the right side of the array, meaning it has unused memory, the method shrinkSize() can free up the extra memory. When all space is consumed, and an additional element is to be added, then the underlying fixed-size array needs to increase in size. Typically resizing is expensive because you have to allocate a bigger array and copy over all of the elements from the array you have outgrown before we can finally append our item.
Simple code for dynamic array. In below code then the array will become full of size we copy all element to new double size array(variable size array).sample code is belowÂ
C++
#include <iostream>using namespace std;Â
class DynamicArray {private:    // Pointer to store array created    // using new keyword    int* array = NULL;    // Size of array    int size;Â
    // Container size    int capacity;Â
public:Â Â Â Â // Default constructor with size 1Â Â Â Â DynamicArray()Â Â Â Â {Â Â Â Â Â Â Â Â capacity = 1;Â Â Â Â Â Â Â Â size = 0;Â Â Â Â Â Â Â Â array = new int[capacity];Â Â Â Â }Â
    // Taking size from the user    DynamicArray(int capacity)    {        this->capacity = capacity;        array = new int[capacity];        size = 0;    }Â
    // Returns the size of Array    // i.e Total elements stored currently    int getSize() { return size; }Â
    // Returns the size of container    int getCapacity() { return capacity; }Â
    // Inserting element after last stored index    void push_back(int value)    {        // check is array having size to store element or        // not        if (size == capacity) {Â
            // if not then grow the array by double            growArray();        }Â
        // insert element        array[size] = value;        // increment the size or last_index+1        size++;    }Â
    // Deleting element at last stored index    void pop_back()    {        // Replace the last index by 0        array[size - 1] = 0;Â
        // Decrement the array size        size--;Â
        // Reduce if the container half element of its        // capacity        if (size == (capacity / 2)) {            shrinkArray();        }    }Â
    // Increase the array size by double of current capacity    void growArray()    {Â
        // Creating new array of double size        int* temp = new int[capacity * 2];Â
        capacity = capacity * 2;        // copy element of old array in newly created array        for (int i = 0; i < size; i++) {            temp[i] = array[i];        }Â
        // Delete old array        delete[] array;Â
        // Assign newly created temp array to original array        array = temp;    }Â
    // Reduce the size of array by half    void shrinkArray()    {Â
        // Creating new array of half size        capacity = size;        int* temp = new int[capacity];Â
        // copy element of old array in newly created array        for (int i = 0; i < size; i++) {            temp[i] = array[i];        }Â
        // Delete old array        delete[] array;Â
        // Assign newly created temp array to original array        array = temp;    }Â
    // Searching element in the given array    int search(int key)    {        for (int i = 0; i < size; i++) {            if (array[i] == key) {                // If element found return its index                return i;            }        }Â
        // Return -1 if element not found;        return -1;    }Â
    // Insert element at given index    void insertAt(int index, int value)    {        // check is array having size to store element or        // not        if (size == capacity) {Â
            // if not then grow the array by double            growArray();        }Â
        for (int i = size - 1; i >= index; i--) {            array[i + 1] = array[i];        }Â
        array[index] = value;        size++;    }Â
    // Delete element at given index    void deleteAt(int index)    {        for (int i = index; i < size; i++) {            array[i] = array[i + 1];        }Â
        // Replace the last index by 0        array[size - 1] = 0;Â
        // Decrement the array size        size--;Â
        // Reduce if the container half element of its        // capacity        if (size == (capacity / 2)) {            shrinkArray();        }    }Â
    // To Print Array    void printArrayDetails()    {        cout << "Elements of array : ";        for (int i = 0; i < size; i++) {            cout << array[i] << " ";        }        cout << endl;        cout << "No of elements in array : " << size             << ", Capacity of array :" << capacity << endl;    }Â
    bool isEmpty()    {        if (size == 0) {            return true;        }        else {            return false;        }    }};Â
int main(){Â Â Â Â DynamicArray da;Â
    da.push_back(1);    da.push_back(2);    da.push_back(3);    da.push_back(4);    da.push_back(5);    da.push_back(6);    da.push_back(7);    da.push_back(8);    da.push_back(9);    da.push_back(10);    da.push_back(11);Â
    da.printArrayDetails();Â
    da.shrinkArray();    cout << "\nCapacity of array after shrinking : "         << da.getCapacity() << endl;Â
    cout << "\nAfter inserting at index 3 " << endl;    da.insertAt(3, 50);    da.printArrayDetails();Â
    cout << "\nAfter delete last element ";    da.pop_back();    da.printArrayDetails();Â
    cout << "\nAfter deleting at index 3 ";    da.deleteAt(3);    da.printArrayDetails();Â
    cout << "\nSearching 5 in array ";    int index = da.search(5);    if (index != -1) {        cout << "Element found at index : " << index << endl;    }    else {        cout << "Element not found " << endl;    }    return 0;}Â
// This code is contributed by Aniket Tiwari |
Java
// Java program deals with all operation of a dynamic array// add, remove, resize memory of array is the main featurepublic class DynamicArray {Â
    // create three variable array[] is a array,    // count will deal with no of element add by you and    // size will with size of array[]    private int array[];    private int count;    private int size;    // constructor initialize value to variableÂ
    public DynamicArray()    {        array = new int[1];        count = 0;        size = 1;    }    // function add an element at the end of arrayÂ
    public void add(int data)    {Â
        // check no of element is equal to size of array        if (count == size) {            growSize(); // make array size double        } // insert element at end of array        array[count] = data;        count++;    }Â
    // function makes size double of array    public void growSize()    {Â
        int temp[] = null;        if (count == size) {Â
            // temp is a double size array of array            // and store array elements            temp = new int[size * 2];            {                for (int i = 0; i < size; i++) {                    // copy all array value into temp                    temp[i] = array[i];                }            }        }Â
        // double size array temp initialize        // into variable array again        array = temp;Â
        // and make size is double also of array        size = size * 2;    }Â
    // function shrink size of array    // which block unnecessary remove them    public void shrinkSize()    {        int temp[] = null;        if (count > 0) {Â
            // temp is a count size array            // and store array elements            temp = new int[count];            for (int i = 0; i < count; i++) {Â
                // copy all array value into temp                temp[i] = array[i];            }Â
            size = count;Â
            // count size array temp initialize            // into variable array again            array = temp;        }    }    // function add an element at given indexÂ
    public void addAt(int index, int data)    {        // if size is not enough make size double        if (count == size) {            growSize();        }Â
        for (int i = count - 1; i >= index; i--) {Â
            // shift all element right            // from given index            array[i + 1] = array[i];        }Â
        // insert data at given index        array[index] = data;        count++;    }Â
    // function remove last element or put    // zero at last index    public void remove()    {        if (count > 0) {            array[count - 1] = 0;            count--;        }    }Â
    // function shift all element of right    // side from given index in left    public void removeAt(int index)    {        if (count > 0) {            for (int i = index; i < count - 1; i++) {Â
                // shift all element of right                // side from given index in left                array[i] = array[i + 1];            }            array[count - 1] = 0;            count--;        }    }Â
    public static void main(String[] args)    {        DynamicArray da = new DynamicArray();Â
        // add 9 elements in array        da.add(1);        da.add(2);        da.add(3);        da.add(4);        da.add(5);        da.add(6);        da.add(7);        da.add(8);        da.add(9);Â
        // print all array elements after add 9 elements        System.out.println("Elements of array:");        for (int i = 0; i < da.size; i++) {            System.out.print(da.array[i] + " ");        }Â
        System.out.println();Â
        // print size of array and no of element        System.out.println("Size of array: " + da.size);        System.out.println("No of elements in array: "                           + da.count);Â
        // shrinkSize of array        da.shrinkSize();Â
        // print all array elements        System.out.println("Elements of array "                           + "after shrinkSize of array:");        for (int i = 0; i < da.size; i++) {            System.out.print(da.array[i] + " ");        }        System.out.println();Â
        // print size of array and no of element        System.out.println("Size of array: " + da.size);        System.out.println("No of elements in array: "                           + da.count);Â
        // add an element at index 1        da.addAt(1, 22);Â
        // print Elements of array after adding an        // element at index 1        System.out.println("Elements of array after"                           + " add an element at index 1:");        for (int i = 0; i < da.size; i++) {            System.out.print(da.array[i] + " ");        }Â
        System.out.println();Â
        // print size of array and no of element        System.out.println("Size of array: " + da.size);        System.out.println("No of elements in array: "                           + da.count);Â
        // delete last element        da.remove();Â
        // print Elements of array after delete last        // element        System.out.println("Elements of array after"                           + " delete last element:");        for (int i = 0; i < da.size; i++) {            System.out.print(da.array[i] + " ");        }Â
        System.out.println();Â
        // print size of array and no of element        System.out.println("Size of array: " + da.size);        System.out.println("No of elements in array: "                           + da.count);Â
        // delete element at index 1        da.removeAt(1);Â
        // print Elements of array after delete        // an element index 1        System.out.println("Elements of array after"                           + " delete element at index 1:");        for (int i = 0; i < da.size; i++) {            System.out.print(da.array[i] + " ");        }        System.out.println();Â
        // print size of array and no of element        System.out.println("Size of array: " + da.size);        System.out.println("No of elements in array: "                           + da.count);    }} |
Python3
# Python 3 program deals with all operation of a dynamic array# add, remove, resize memory of array is the main featureÂ
Â
class DynamicArray:Â
    # create three variable array[] is a array,    # count will deal with no of element add by you and    # size will with size of array[]    array = None    count = 0    size = 0Â
    # constructor initialize value to variable    def __init__(self):        self.array = [0] * (1)        self.count = 0        self.size = 1Â
    # function add an element at the end of array    def add(self, data):Â
        # check no of element is equal to size of array        if (self.count == self.size):            self.growSize()Â
        # insert element at end of array        self.array[self.count] = data        self.count += 1Â
    # function makes size double of array    def growSize(self):        temp = None        if (self.count == self.size):Â
            # temp is a double size array of array            # and store array elements            temp = [0] * (self.size * 2)            i = 0            while (i < self.size):Â
                # copy all array value into temp                temp[i] = self.array[i]                i += 1Â
        # double size array temp initialize        # into variable array again        self.array = tempÂ
        # and make size is double also of array        self.size = self.size * 2Â
    # function shrink size of array    # which block unnecessary remove them    def shrinkSize(self):        temp = None        if (self.count > 0):Â
            # temp is a count size array            # and store array elements            temp = [0] * (self.count)            i = 0            while (i < self.count):Â
                # copy all array value into temp                temp[i] = self.array[i]                i += 1            self.size = self.countÂ
            # count size array temp initialize            # into variable array again            self.array = tempÂ
    # function add an element at given index    def addAt(self, index, data):Â
        # if size is not enough make size double        if (self.count == self.size):            self.growSize()        i = self.count - 1        while (i >= index):Â
            # shift all element right            # from given index            self.array[i + 1] = self.array[i]            i -= 1Â
        # insert data at given index        self.array[index] = data        self.count += 1Â
    # function remove last element or put    # zero at last index    def remove(self):        if (self.count > 0):            self.array[self.count - 1] = 0            self.count -= 1    # function shift all element of right    # side from given index in leftÂ
    def removeAt(self, index):        if (self.count > 0):            i = index            while (i < self.count - 1):Â
                # shift all element of right                # side from given index in left                self.array[i] = self.array[i + 1]                i += 1            self.array[self.count - 1] = 0            self.count -= 1Â
    @staticmethod    def main(args):        da = DynamicArray()Â
        # add 9 elements in array        da.add(1)        da.add(2)        da.add(3)        da.add(4)        da.add(5)        da.add(6)        da.add(7)        da.add(8)        da.add(9)Â
        # print all array elements after add 9 elements        print("Elements of array:")        i = 0        while (i < da.size):            print(str(da.array[i]) + " ", end="")            i += 1        print()Â
        # print size of array and no of element        print("Size of array: " + str(da.size))        print("No of elements in array: " + str(da.count))Â
        # shrinkSize of array        da.shrinkSize()Â
        # print all array elements        print("Elements of array after shrinkSize of array:")        i = 0        while (i < da.size):            print(str(da.array[i]) + " ", end="")            i += 1        print()Â
        # print size of array and no of element        print("Size of array: " + str(da.size))        print("No of elements in array: " + str(da.count))Â
        # add an element at index 1        da.addAt(1, 22)Â
        # print Elements of array after adding an        # element at index 1        print("Elements of array after add an element at index 1:")        i = 0        while (i < da.size):            print(str(da.array[i]) + " ", end="")            i += 1        print()Â
        # print size of array and no of element        print("Size of array: " + str(da.size))        print("No of elements in array: " + str(da.count))Â
        # delete last element        da.remove()Â
        # print Elements of array after delete last        # element        print("Elements of array after delete last element:")        i = 0        while (i < da.size):            print(str(da.array[i]) + " ", end="")            i += 1        print()Â
        # print size of array and no of element        print("Size of array: " + str(da.size))        print("No of elements in array: " + str(da.count))Â
        # delete element at index 1        da.removeAt(1)Â
        # print Elements of array after delete        # an element index 1        print("Elements of array after delete element at index 1:")        i = 0        while (i < da.size):            print(str(da.array[i]) + " ", end="")            i += 1        print()Â
        # print size of array and no of element        print("Size of array: " + str(da.size))        print("No of elements in array: " + str(da.count))Â
Â
# Driver codeif __name__ == "__main__":Â Â Â Â DynamicArray.main([])Â
    # This code is contributed by aadityaburujwale. |
C#
// C# program deals with all operation// of dynamic array add, remove, resize// memory of array is the main featureusing System;Â
public class DynamicArray {Â
    // create three variable array[] is    // a array, count will deal with no    // of element add by you and    // size will with size of array[]    private int[] array;    private int count;    private int size;Â
    // constructor initialize value to variable    public DynamicArray()    {        array = new int[1];        count = 0;        size = 1;    }Â
    // function add an element at the end of array    public void add(int data)    {Â
        // check no of element is equal to size of array        if (count == size) {            growSize(); // make array size double        }Â
        // insert element at end of array        array[count] = data;        count++;    }Â
    // function makes size double of array    public void growSize()    {Â
        int[] temp = null;        if (count == size) {Â
            // temp is a double size array of array            // and store array elements            temp = new int[size * 2];            {                for (int i = 0; i < size; i++) {                    // copy all array value into temp                    temp[i] = array[i];                }            }        }Â
        // double size array temp initialize        // into variable array again        array = temp;Â
        // and make size is double also of array        size = size * 2;    }Â
    // function shrink size of array    // which block unnecessary remove them    public void shrinkSize()    {        int[] temp = null;        if (count > 0) {Â
            // temp is a count size array            // and store array elements            temp = new int[count];            for (int i = 0; i < count; i++) {Â
                // copy all array value into temp                temp[i] = array[i];            }Â
            size = count;Â
            // count size array temp initialize            // into variable array again            array = temp;        }    }Â
    // function add an element at given index    public void addAt(int index, int data)    {        // if size is not enough make size double        if (count == size) {            growSize();        }Â
        for (int i = count - 1; i >= index; i--) {Â
            // shift all element right            // from given index            array[i + 1] = array[i];        }Â
        // insert data at given index        array[index] = data;        count++;    }Â
    // function remove last element or put    // zero at last index    public void remove()    {        if (count > 0) {            array[count - 1] = 0;            count--;        }    }Â
    // function shift all element of right    // side from given index in left    public void removeAt(int index)    {        if (count > 0) {            for (int i = index; i < count - 1; i++) {Â
                // shift all element of right                // side from given index in left                array[i] = array[i + 1];            }            array[count - 1] = 0;            count--;        }    }Â
    // Driver code    public static void Main()    {        DynamicArray da = new DynamicArray();Â
        // add 9 elements in array        da.add(1);        da.add(2);        da.add(3);        da.add(4);        da.add(5);        da.add(6);        da.add(7);        da.add(8);        da.add(9);Â
        // print all array elements after add 9 elements        Console.WriteLine("Elements of array:");        for (int i = 0; i < da.size; i++) {            Console.Write(da.array[i] + " ");        }Â
        Console.WriteLine();Â
        // print size of array and no of element        Console.WriteLine("Size of array: " + da.size);        Console.WriteLine("No of elements in array: "                          + da.count);Â
        // shrinkSize of array        da.shrinkSize();Â
        // print all array elements        Console.WriteLine("Elements of array "                          + "after shrinkSize of array:");        for (int i = 0; i < da.size; i++) {            Console.Write(da.array[i] + " ");        }        Console.WriteLine();Â
        // print size of array and no of element        Console.WriteLine("Size of array: " + da.size);        Console.WriteLine("No of elements in array: "                          + da.count);Â
        // add an element at index 1        da.addAt(1, 22);Â
        // print Elements of array after adding an        // element at index 1        Console.WriteLine("Elements of array after"                          + " add an element at index 1:");        for (int i = 0; i < da.size; i++) {            Console.Write(da.array[i] + " ");        }Â
        Console.WriteLine();Â
        // print size of array and no of element        Console.WriteLine("Size of array: " + da.size);        Console.WriteLine("No of elements in array: "                          + da.count);Â
        // delete last element        da.remove();Â
        // print Elements of array after delete last        // element        Console.WriteLine("Elements of array after"                          + " delete last element:");        for (int i = 0; i < da.size; i++) {            Console.Write(da.array[i] + " ");        }Â
        Console.WriteLine();Â
        // print size of array and no of element        Console.WriteLine("Size of array: " + da.size);        Console.WriteLine("No of elements in array: "                          + da.count);Â
        // delete element at index 1        da.removeAt(1);Â
        // print Elements of array after delete        // an element index 1        Console.WriteLine("Elements of array after"                          + " delete element at index 1:");        for (int i = 0; i < da.size; i++) {            Console.Write(da.array[i] + " ");        }        Console.WriteLine();Â
        // print size of array and no of element        Console.WriteLine("Size of array: " + da.size);        Console.WriteLine("No of elements in array: "                          + da.count);    }}Â
/* This code contributed by PrinciRaj1992 */ |
Javascript
class DynamicArray {    // Pointer to store array created using new keyword    #array;    // Size of array    #size;    // Container size    #capacity;Â
    // Default constructor with size 1    constructor() {        this.#capacity = 1;        this.#size = 0;        this.#array = new Array(this.#capacity);    }Â
    // Taking size from the user    // constructor(capacity) {    // this.#capacity = capacity;    // this.#array = new Array(this.#capacity);    // this.#size = 0;    // }Â
    // Returns the size of Array i.e Total elements stored currently    getSize() {        return this.#size;    }Â
    // Returns the size of container    getCapacity() {        return this.#capacity;    }Â
    // Inserting element after last stored index    push_back(value) {        // check is array having size to store element or not        if (this.#size == this.#capacity) {            // if not then grow the array by double            this.growArray();        }        // insert element        this.#array[this.#size] = value;        // increment the size or last_index+1        this.#size++;    }Â
    // Deleting element at last stored index    pop_back() {        // Replace the last index by 0        this.#array[this.#size - 1] = 0;        // Decrement the array size        this.#size--;        // Reduce if the container half element of its capacity        if (this.#size == Math.floor(this.#capacity / 2)) {            this.shrinkArray();        }    }Â
    // Increase the array size by double of current capacity    growArray() {        // Creating new array of double size        let temp = new Array(this.#capacity * 2);        this.#capacity = this.#capacity * 2;        // copy element of old array in newly created array        for (let i = 0; i < this.#size; i++) {            temp[i] = this.#array[i];        }        // Delete old array        this.#array = null;        // Assign newly created temp array to original array        this.#array = temp;    }Â
    // Reduce the size of array by half    shrinkArray() {        // Creating new array of half size        this.#capacity = this.#size;        let temp = new Array(this.#capacity);        // copy element of old array in newly created array        for (let i = 0; i < this.#size; i++) {            temp[i] = this.#array[i];        }        // Delete old array        this.#array = null;        // Assign newly created temp array to original array        this.#array = temp;    }Â
    // Searching element in the given array    search(key) {        for (let i = 0; i < this.#size; i++) {            if (this.#array[i] == key) {                // If element found return its index                return i;            }        }        // Return -1 if element not found;        return -1;    }Â
    // Insert element at given index    insertAt(index, value) {        // check is array having size to store element or not        if (this.#size == this.#capacity) {            // if not then grow the array by double            this.growArray();        }        for (let i = this.#size - 1; i >= index; i--) {            this.#array[i + 1] = this.#array[i];        }        this.#array[index] = value;        this.#size++;    }Â
    // Delete element at given index    // Delete element at given index    deleteAt(index) {        for (let i = index; i < this.#size; i++) {            this.#array[i] = this.#array[i + 1];        }Â
        // Replace the last index by 0        this.#array[this.#size - 1] = 0;Â
        // Decrement the array size        this.#size--;Â
        // Reduce if the container half element of its        // capacity        if (this.#size == (this.#capacity / 2)) {            shrinkArray();        }    }Â
    // To Print Array    printArrayDetails() {        console.log("Elements of array : ");        console.log(this.#array);        console.log("No of elements in array : ", this.#size            , ", Capacity of array :", this.#capacity);    }Â
    isEmpty() {        if (size == 0) {            return true;        }        else {            return false;        }    }};Â
const da = new DynamicArray();Â
da.push_back(1);da.push_back(2);da.push_back(3);da.push_back(4);da.push_back(5);da.push_back(6);da.push_back(7);da.push_back(8);da.push_back(9);da.push_back(10);da.push_back(11);Â
da.printArrayDetails();Â
da.shrinkArray();console.log("\nCapacity of array after shrinking : "    , da.getCapacity());Â
console.log("\nAfter inserting at index 3 ");da.insertAt(3, 50);da.printArrayDetails();Â
console.log("\nAfter delete last element ");da.pop_back();da.printArrayDetails();Â
console.log("\nAfter deleting at index 3 ");da.deleteAt(3);da.printArrayDetails();Â
console.log("\nSearching 5 in array ");let index = da.search(5);if (index >= 0) {Â Â Â Â console.log("Element found at index : ", index);}else {Â Â Â Â console.log("Element not found ");}Â
// This code is contributed by akashish__ |
Elements of array : 1 2 3 4 5 6 7 8 9 10 11 No of elements in array : 11, Capacity of array :16 Capacity of array after shrinking : 11 After inserting at index 3 Elements of array : 1 2 3 50 4 5 6 7 8 9 10 11 No of elements in array : 12, Capacity of array :22 After delete last element Elements of array : 1 2 3 50 4 5 6 7 8 9 10 No of elements in array : 11, Capacity of array :11 After deleting at index 3 Elements of array : 1 2 3 4 5 6 7 8 9 10 No of elements in array : 10, Capacity of array :11 Searching 5 in array Element found at index : 4
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


[…] Is it possible to create dynamic array? […]