DSA Array
DSA Array
❮ PreviousNext ❯
Arrays
An array is a data structure used to store multiple elements.
For example, an algorithm can be used to look through an array to find the
lowest value, like the animation below shows:
Speed:
Find Lowest
Lowest value:
Arrays are indexed, meaning that each element in the array has an index, a
number that says where in the array the element is located. The programming
languages in this tutorial (Python, Java, and C) use zero-based indexing for
arrays, meaning that the first element in an array can be accessed at index 0.
In Python, this code use index 0 to write the first array element (value 7) to the
console:
Example
Python:
Run Example »
How it works:
Try the simulation below to see how the algorithm for finding the lowest value
works (the animation is the same as the one on the top of this page):
Speed:
Find Lowest
Lowest value:
This next simulation also finds the lowest value in an array, just like the
simulation above, but here we can see how the numbers inside the array are
checked to find the lowest value:
If you can write down the algorithm in something between human language and
programming language, the algorithm will be easier to implement later because
we avoid drowning in all the details of the programming language syntax.
1. Create a variable 'minVal' and set it equal to the first value of the array.
2. Go through every element in the array.
3. If the current element has a lower value than 'minVal', update 'minVal' to
this value.
4. After looking at all the elements in the array, the 'minVal' variable now
contains the lowest value.
You can also write the algorithm in a way that looks more like a programming
language if you want to, like this:
After we have written down the algorithm, it is much easier to implement the
algorithm in a specific programming language:
Example
Python:
minVal = i
print('Lowest value: ',minVal) # Step 4
Run Example »
When exploring algorithms, we often look at how long time an algorithm takes
to run relative to the size of the data set.
In the example above, the time the algorithm needs to run is proportional, or
linear, to the size of the data set. This is because the algorithm must visit every
array element one time to find the lowest value. The loop must run 5 times since
there are 5 values in the array. And if the array had 1000 values, the loop would
have to run 1000 times.
Try the simulation below to see this relationship between the number of
compare operations needed to find the lowest value, and the size of the array.
See this page for a more thorough explanation of what time complexity is.
Each algorithm in this tutorial will be presented together with its time
complexity.
Random
Descending
Ascending
10 Random
Operations: 0
Run Clear
DSA Exercises
Test Yourself With Exercises
Exercise:
How can we print value "7" from the array below?