….
DSA Arrays
Arrays are one of the most fundamental data structures in computer science. They provide a way to store multiple elements in a single, ordered collection.
Think of an array like a row of lockers in a hallway: each locker has a number (index) and holds a value.
🔹 What is an Array?
- An array is a collection of elements stored at contiguous memory locations.
- Each element can be accessed directly using its index.
- Arrays make it easy to perform operations such as searching, sorting, and iteration.
📌 Why use arrays?
- Easy to access elements by index (constant time, O(1)).
- Compact and memory-friendly compared to some other data structures.
- Widely supported across programming languages.
🔹 Arrays in Python, Java, and C
Python Example:
my_array = [10, 25, 7, 14, 32]
print(my_array[0]) # Output: 10
👉 In Python, arrays are represented by lists.
Java Example:
int[] myArray = {10, 25, 7, 14, 32};
System.out.println(myArray[0]); // Output: 10
C Example:
#include <stdio.h>
int main() {
int myArray[] = {10, 25, 7, 14, 32};
printf("%d", myArray[0]); // Output: 10
return 0;
}
🔹 Array Indexing
- Arrays are zero-indexed in most programming languages.
- This means the first element is at index 0, the second at index 1, and so on.
For example:
Array: [10, 25, 7, 14, 32]
Index: 0 1 2 3 4
So, my_array[2]
will give you 7.
🔹 Algorithm: Find the Minimum Value in an Array
Let’s write our first algorithm using arrays!
Goal: Find the smallest number in an array.
Step-by-step logic:
- Start with the first element and assume it’s the smallest.
- Go through the array, one element at a time.
- If you find a smaller element, update your “minimum”.
- At the end, you’ll have the lowest value.
Pseudocode:
minVal = array[0]
for each element in array:
if element < minVal:
minVal = element
return minVal
Python Implementation:
my_array = [10, 25, 7, 14, 32]
minVal = my_array[0]
for value in my_array:
if value < minVal:
minVal = value
print("Lowest value:", minVal)
🔹 Time Complexity Analysis
- This algorithm must check every element once.
- If the array has
n
elements, the loop runsn
times. - Therefore, the time complexity is O(n).
👉 If the array has:
- 5 elements → 5 comparisons
- 100 elements → 100 comparisons
- 1,000,000 elements → 1,000,000 comparisons
📊 The relationship is linear: double the input size, double the work.
🔹 Space Complexity
- We only used one extra variable (
minVal
). - This means the space complexity is O(1) (constant space).
✅ Key Takeaways
- Arrays are ordered collections with indexed access.
- They allow fast lookups (O(1)), but some operations (like finding the minimum) require scanning the entire array.
- Understanding arrays is the first step to mastering more complex data structures.