Arrays in Programming Explained Simply — DSA for Beginners

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MyrinNew
    Senior Member
    • Feb 2024
    • 5168

    #1

    Arrays in Programming Explained Simply — DSA for Beginners

    The array is the most fundamental data structure in programming. Almost every complex structure — stacks, queues, heaps — is built on top of arrays internally.


    📦 What is an Array?

    An array stores elements in continuous memory locations, each accessible by an index starting at 0.






    const fruits = ['Apple', 'Banana', 'Eggs', 'Juice'];
    // fruits[0] = 'Apple', fruits[2] = 'Eggs'







    If you want Eggs → directly go to index 2. No searching. That's the power of arrays.


    ⚡ How Arrays Work Internally

    Arrays are stored in contiguous memory. This is why random access is O(1) — the computer calculates the address directly: base + (index × element_size).


    🔑 Key Operations & Complexity

    Access arr[i] O(1) Direct memory jump
    Search for value O(n) Must check each element
    Insert at end O(1) Append to last slot
    Insert at middle O(n) Must shift all elements right
    Delete at middle O(n) Must shift all elements left


    💻 Common Array Operations in JavaScript





    const arr = [10, 20, 30, 40];
    console.log(arr[2]); // 30 — O(1)
    arr.push(50); // O(1) — insert at end
    arr.unshift(5); // O(n) — shifts everything
    arr.pop(); // O(1) — delete last
    arr.indexOf(30); // O(n) — linear scan







    ⚠️ When NOT to Use Arrays

    • Frequent middle inserts/deletes → Use Linked List
    • Key-value lookups → Use Hash Map
    • LIFO operations → Use Stack





    Part 3 of the Bitveen DSA Series. Originally published at bitveen.com




    More...
Working...