Getting Started with Array Data Structure
Array is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. In this article, we have decided to provide a complete guide for Arrays, which will help you to tackle any problem based on Arrays.
Table of Content
- What is an Array?
- Basic terminologies of array
- Memory representation of Array
- Declaration of Array
- Initialization of Array
- Importance of Array
- Types of arrays
- Operations on Array
- Complexity Analysis of Operations on Array
- Advantages of Array
- Disadvantages of Array
- Applications of Array
- Top theoretical interview questions
- Frequently Asked Questions (FAQs) on Arrays:
What is an Array?
Array is a linear data structure that stores a collection of items of same data type in contiguous memory locations. Each item in an array is indexed starting with 0. We can directly access an array element by using its index value.
Basic terminologies of Array
- Array Index: In an array, elements are identified by their indexes. Array index starts from 0.
- Array element: Elements are items stored in an array and can be accessed by their index.
- Array Length: The length of an array is determined by the number of elements it can contain.
Memory representation of Array
In an array, all the elements are stored in contiguous memory locations. So, if we initialize an array
Declaration of Array
Arrays can be declared in various ways in different languages. For better illustration, below are some language-specific array declarations:
// This array will store integer type element
int arr[5];
// This array will store char type element
char arr[10];
// This array will store float type element
float arr[20];
// This array will store integer type element
int arr[5];
// This array will store char type element
char arr[10];
// This array will store float type element
float arr[20];
// This array will store integer type element
int arr[];
// This array will store char type element
char arr[];
// This array will store float type element
float arr[];
import array
# This array will store integer type element
arr = array.array('i')
# This array will store char type element
arr = array.array('b')
# This array will store float type element
arr = array.array('f')
// This array will store integer type element
int[] arr;
// This array will store char type element
char[] arr2;
// This array will store float type element
float[] arr3;
// JS code
let arr=[]
Initialization of Array
Arrays can be initialized in different ways in different languages. Below are some language-specific array initializations:
int arr[] = { 1, 2, 3, 4, 5 };
char arr[5] = { 'a', 'b', 'c', 'd', 'e' };
float arr[10] = { 1.4, 2.0, 24, 5.0, 0.0 };
int arr[] = { 1, 2, 3, 4, 5 };
char arr[5] = { 'a', 'b', 'c', 'd', 'e' };
float arr[10] = { 1.4, 2.0, 24, 5.0, 0.0 };
int arr[] = { 1, 2, 3, 4, 5 };
char arr[] = { 'a', 'b', 'c', 'd', 'e' };
float arr[] = { 1.4f, 2.0f, 24f, 5.0f, 0.0f };
import array
# This array will store integer type element
arr = array.array('i', [1, 2, 3, 4, 5])
# This array will store char type element
arr = array.array('b', [])
# This array will store float type element
arr = array.array('f')
int[] arr = { 1, 2, 3, 4, 5 };
char[] arr = { 'a', 'b', 'c', 'd', 'e' };
float[] arr = { 1.4f, 2.0f, 24f, 5.0f, 0.0f };
let arr = [ 1, 2, 3, 4, 5 ];
let arr = [ 'a', 'b', 'c', 'd', 'e' ];
let arr = [ 1.4, 2.0, 24, 5.0, 0.0 ];
Importance of Array
Assume there is a class of five students and if we have to keep records of their marks in examination then, we can do this by declaring five variables individual and keeping track of records but what if the number of students becomes very large, it would be challenging to manipulate and maintain the data.
What it means is that, we can use normal variables (v1, v2, v3, ..) when we have a small number of objects. But if we want to store a large number of instances, it becomes difficult to manage them with normal variables. The idea of an array is to represent many instances in one variable.
Types of Arrays
Arrays can be classified in two ways:
- On the basis of Memory Allocation
- On the basis of Dimensions
Types of Arrays on the basis of Memory Allocation:
1. Static Arrays:
In this type of array, memory is allocated at compile time having a fixed size of it. We cannot alter or update the size of this array. This type of memory allocation is also known as static or compile-time memory allocation. Here only a fixed size (i,e. the size that is mentioned in square brackets []) of memory will be allocated for storage. In case, we don’t know the size of the array then if we declare a larger size and store a lesser number of elements will result in a wastage of memory or or we declare a lesser size than the number of elements then we won’t get enough memory to store all the elements. In such cases, static memory allocation is not preferred.
//Static Integer Array
int arr[5] = {1, 2, 3, 4, 5};
//Static Integer Array
int arr[5] = {1, 2, 3, 4, 5};
// Static Array
int[] arr = { 1, 2, 3, 4, 5 };
import array
# Static Array
arr = array.array('i', [1, 2, 3, 4, 5])
// Static array
int[] arr = { 1, 2, 3, 4, 5 };
let arr[] = {1, 2, 3, 4, 5}
2. Dynamic Arrays:
In this type of array, memory is allocated at run time but not having a fixed size. Suppose, a user wants to declare any random size of an array, then we will not use a static array, instead of that a dynamic array is used. This type of memory allocation is also known as dynamic or run-time memory allocation. It is used to specify the size of it during the run time of any program.
// Dynamic Integer Array
int* arr = new int[5];
// Dynamic Integer Array
int* arr = malloc(sizeof(int) * 5);
// Dynamic Integer Array
ArrayList<Integer> arr = new ArrayList<>();
# Dynamic Array
arr = []
// Dynamic Integer Array
int[] arr = new int[5];
// Dynamic Array
let arr = new Array(5);
Types of Arrays on the basis of Dimensions:
1. One-dimensional Array(1-D Array): You can imagine a 1d array as a row, where elements are stored one after another.
2. Multi-dimensional Array: A multi-dimensional array is an array with more than one dimension. We can use multidimensional array to store complex data in the form of tables, etc. We can have 2-D arrays, 3-D arrays, 4-D arrays and so on.
- Two-Dimensional Array(2-D Array or Matrix): 2-D Multidimensional arrays can be considered as an array of arrays or as a matrix consisting of rows and columns.
- Three-Dimensional Array(3-D Array): A 3-D Multidimensional array contains three dimensions, so it can be considered an array of two-dimensional arrays.
Operations on Array
1. Array Traversal:
Array traversal involves visiting all the elements of the array once. Below is the implementation of Array traversal in different Languages:
int arr[] = { 1, 2, 3, 4, 5 };
int len = sizeof(arr) / sizeof(arr[0]);
// Traversing over arr[]
for (int i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
int arr[] = { 1, 2, 3, 4, 5 };
// Traversing over arr[]
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
import array
arr = array.array('i', [1, 2, 3, 4, 5])
# Traversing over arr[]
for x in arr:
print(x, end=" ")
int[] arr = { 1, 2, 3, 4, 5 };
// Traversing over arr[]
for (int i = 0; i < arr.Length; i++)
Console.Write(" " + arr[i]);
let arr = [1, 2, 3, 4, 5]
// Traversing over arr[]
for (let x of arr)
console.log(x)
int arr[] = { 1, 2, 3, 4, 5 };
int len = sizeof(arr) / sizeof(arr[0]);
// Traversing over arr[]
for (int i = 0; i < len; i++) {
cout << arr[i] << " ";
2. Insertion in Array:
We can insert one or multiple elements at any position in the array. Below is the implementation of Insertion in Array in different languages:
// Function to insert element
// at a specific position
void insertElement(int arr[], int n, int x, int pos)
{
// shift elements to the right
// which are on the right side of pos
for (int i = n - 1; i >= pos; i--)
arr[i + 1] = arr[i];
arr[pos] = x;
}
// Function to insert element
// at a specific position
void insertElement(int arr[], int n, int x, int pos)
{
// shift elements to the right
// which are on the right side of pos
for (int i = n - 1; i >= pos; i--)
arr[i + 1] = arr[i];
arr[pos] = x;
}
static void insertElement(int arr[], int n, int x, int pos)
{
// shift elements to the right
// which are on the right side of pos
for (int i = n - 1; i >= pos; i--)
arr[i + 1] = arr[i];
arr[pos] = x;
}
# python Program to Insert an element
# at a specific position in an Array
def insertElement(arr, n, x, pos):
# shift elements to the right
# which are on the right side of pos
for i in range(n-1, pos-1, -1):
arr[i + 1] = arr[i]
arr[pos] = x
static void insertElement(int[] arr, int n, int x, int pos)
{
// shift elements to the right
// which are on the right side of pos
for (int i = n - 1; i >= pos; i--)
arr[i + 1] = arr[i];
arr[pos] = x;
}
// javascript Program to Insert an element
// at a specific position in an Array
function insertElement(arr, n, x, pos)
{
// shift elements to the right
// which are on the right side of pos
var i = n - 1;
for (i; i >= pos; i--)
{
arr[i + 1] = arr[i];
}
arr[pos] = x;
}
Deletion in Array:
We can delete an element at any index in an array. Below is the implementation of Deletion of element in an array:
// To search a key to be deleted
int findElement(int arr[], int n, int key);
// Function to delete an element
int deleteElement(int arr[], int n, int key)
{
// Find position of element to be deleted
int pos = findElement(arr, n, key);
if (pos == -1) {
cout << "Element not found";
return n;
}
// Deleting element
int i;
for (i = pos; i < n - 1; i++)
arr[i] = arr[i + 1];
return n - 1;
}
// Function to implement search operation
int findElement(int arr[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
// Return -1 if key is not found
return -1;
}
#include <iostream>
using namespace std;
int main() {
cout << "GFG!";
return 0;
}
// C program to implement delete operation in a
// unsorted array
#include <stdio.h>
// To search a key to be deleted
int findElement(int arr[], int n, int key);
// Function to delete an element
int deleteElement(int arr[], int n, int key)
{
// Find position of element to be deleted
int pos = findElement(arr, n, key);
if (pos == -1) {
printf("Element not found");
return n;
}
// Deleting element
int i;
for (i = pos; i < n - 1; i++)
arr[i] = arr[i + 1];
return n - 1;
}
// Function to implement search operation
int findElement(int arr[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
// Return -1 if key is not found
return -1;
}
// function to search a key to
// be deleted
static int findElement(int arr[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
// Return -1 if key is not found
return -1;
}
// Function to delete an element
static int deleteElement(int arr[], int n, int key)
{
// Find position of element to be
// deleted
int pos = findElement(arr, n, key);
if (pos == -1) {
System.out.println("Element not found");
return n;
}
// Deleting element
int i;
for (i = pos; i < n - 1; i++)
arr[i] = arr[i + 1];
return n - 1;
}
from array import array
# Function to search for a key in the array
def findElement(arr, n, key):
for i in range(n):
# Return the index if key is found
if arr[i] == key:
return i
# Return -1 if key is not found
return -1
# Function to delete an element from the array
def deleteElement(arr, n, key):
# Find position of element to be deleted
pos = findElement(arr, n, key)
if pos == -1:
print("Element not found")
return n
# Deleting element
for i in range(pos, n - 1):
arr[i] = arr[i + 1]
return n - 1
int findElement(int[] arr, int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
return -1;
}
// Function to delete an element
int deleteElement(int[] arr, int n, int key)
{
// Find position of element
// to be deleted
int pos = findElement(arr, n, key);
if (pos == -1) {
Console.WriteLine("Element not found");
return n;
}
// Deleting element
int i;
for (i = pos; i < n - 1; i++)
arr[i] = arr[i + 1];
return n - 1;
}
// function to search a key to be deleted
function findElement(arr,n,key)
{
let i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
return -1;
}
// Function to delete an element
function deleteElement(arr,n,key)
{
// Find position of element to be deleted
let pos = findElement(arr, n, key);
if (pos == -1)
{
document.write("Element not found");
return n;
}
// Deleting element
let i;
for (i = pos; i< n - 1; i++)
arr[i] = arr[i + 1];
return n - 1;
}
Searching in Array:
We can traverse over an array and search for an element. Below is the implementation of Deletion of element in an array:
// Function to implement search operation
int findElement(int arr[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
// If the key is not found
return -1;
}
// Function to implement search operation
int findElement(int arr[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
// If the key is not found
return -1;
}
// Function to implement search operation
int findElement(int arr[], int n, int key)
{
for (int i = 0; i < n; i++)
if (arr[i] == key)
return i;
// If the key is not found
return -1;
}
# Python program for searching in
# unsorted array
def findElement(arr, n, key):
for i in range(n):
if (arr[i] == key):
return i
# If the key is not found
return -1
// Function to implement
// search operation
int findElement(int[] arr, int n, int key)
{
for (int i = 0; i < n; i++)
if (arr[i] == key)
return i;
// If the key is not found
return -1;
}
// Function to implement search operation
function findElement( arr, n, key)
{
let i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
return -1;
}
Complexity Analysis of Operations on Array
Time Complexity:
Operation | Best Case | Average Case | Worst Case |
---|---|---|---|
Traversal | Ω(N) | θ(N) | O(N) |
Insertion | Ω(1) | θ(N) | O(N) |
Deletion | Ω(1) | θ(N) | O(N) |
Searching | Ω(1) | θ(N) | O(N) |
Space Complexity:
Operation | Best Case | Average Case | Worst Case |
---|---|---|---|
Traversal | Ω(1) | θ(1) | O(1) |
Insertion | Ω(1) | θ(N) | O(N) |
Deletion | Ω(1) | θ(N) | O(N) |
Searching | Ω(1) | θ(1) | O(1) |
Advantages of Array
- Arrays allow random access to elements. This makes accessing elements by position faster.
- Arrays have better cache locality which makes a pretty big difference in performance.
- Arrays represent multiple data items of the same type using a single name.
- Arrays are used to implement the other data structures like linked lists, stacks, queues, trees, graphs, etc.
Disadvantages of Array
- As arrays have a fixed size, once the memory is allocated to them, it cannot be increased or decreased, making it impossible to store extra data if required. An array of fixed size is referred to as a static array.
- Allocating less memory than required to an array leads to loss of data.
- An array is homogeneous in nature so, a single array cannot store values of different data types.
- Arrays store data in contiguous memory locations, which makes deletion and insertion very difficult to implement. This problem is overcome by implementing linked lists, which allow elements to be accessed sequentially.
Applications of Array
- They are used in the implementation of other data structures such as array lists, heaps, hash tables, vectors, and matrices.
- Database records are usually implemented as arrays.
- It is used in lookup tables by computer.
Conclusion
After the discussion, we concluded that arrays are a simple method of accessing elements of the same type by grouping them and we can find the elements efficiently by their indexes and can perform different operations using them. Thus, they are more efficient when it comes to memory allocation and should be used in all modern programming languages. So, this becomes a favorite topic for the perspective of the interview and most of the companies generally asked about the problems on the array. For all these reasons, we must have a good knowledge of it.
Related articles:
- Top 50 Array Coding Problems for Interviews
- How to start learning DSA?
- Competitive Programming – A Complete Guide
- How can one become good at Data Structures and Algorithms easily?
- Why Data Structures and Algorithms Are Important to Learn?
- Top 15 Websites for Coding Challenges and competitions
- SDE SHEET – A Complete Guide for SDE Preparation
- Amazon SDE Sheet – A Guide for Amazon SDE Interview Preparation
- Google Interview Preparation For Software Engineer – A Complete Guide
- 100 Days of Code – A Complete Guide For Beginners and Experienced
Frequently Asked Questions (FAQs) on Arrays
1. What is an array in data structure with example?
An array is a collection of items of the same data type stored at contiguous memory locations. Ex. int arr[5] = {1,2,3,4,5};
2. Why array is a data structure?
Arrays store elements of the same type, they are classified as homogeneous data structures. They can store numbers, strings, characters, boolean values (true and false), objects, and so on.
3. What data structure is an array?
An array is a linear data structure that stores similar elements in contiguous memory locations.
4. What are the types of arrays?
There are majorly two types of arrays:
- One dimensional array
- Multidimensional array
5. How is data stored in an array?
An array is a collection of items of the same data type stored at contiguous memory locations or says the elements are stored one after another in memory. An array uses an index system starting at 0 and going to (n-1), where n is its size.
6. Difference between array and structure?
The structure can contain variables of different types but an array only contains variables of the same type.
7. What are the limitations of an array?
An array is a collection of items of the same data type. That means, in an integer array only integer values can be stored, while in a float array only floating values and character array can have only characters. Thus, no array can have values of two data types.
8. What are the advantages of an array?
There are multiple advantages of array data structure and some of them are:
- Arrays allow random access to elements. This makes accessing elements by position faster.
- Arrays store multiple data of similar types with the same name.
- Array data structures are used to implement the other data structures like linked lists, stacks, queues, trees, graphs, etc.
9. What is the purpose of using arrays?
An array is used when several variables of the same type need to be used, and it can be defined as a sequence of objects of the same type.
10. What is a multidimensional array?
A multi-dimensional array can be termed as an array of arrays that stores homogeneous data in tabular form. Data in Multidimensional Arrays are stored in row-major order.
Contact Us