Operation on Arrays

Photo by Ben Wicks on Unsplash

Operation on Arrays

In this article and upcoming articles, we are going to discuss operation on an array.

Searching

First, in this article let's discuss searching an element in an unsorted array.

Here we have an array. Input as follows See below code

// Input 
arr[] = { 20, 30, 10, 60 , 45 }
x = 30
//Output 1

Now let's try to find the solution to this problem.

int search (int arr[], int n, int x) 
{
    for(int i =0;i<n;i++) {
        if(arr[i] == x) {
            return i;
        }
    }
    return -1;
}

The time complexity of the operation: O(n)

Sorted Array

If we have a sorted array then we can find the element in an array in logN time by using Binary Search. We will discuss binary search in some other articles. For now, we can use the above method for searching in sorted arrays in linear time complexity.

Insert Operation

In fixed size array. If the capacity of an array is equal to the length of the array then we can't insert an element to the array.

// arr = [5,10,20,_,_];
// n = length of an array 
// x = element to be inserted
// cap = capacity of an array 
// pos = position where x to be inserted
int insert(int arr[], int n, int x, int cap,int pos){
    if(n == cap){
        return n;
    }
    int idx = pos - 1;
    for(int i = n - 1; i >= idx; i--) 
        arr[i+1] = arr[i]
    arr[idx] = x;
    return n + 1; 
}

Here in the above code, we are checking if the length of the array and capacity of the array is the same then we are just returning the array. Else we will loop through the array from position n and decrease the index. Once we are at the position of pos then we insert the element and shift the rest of the element to its right.

The time complexity of insertion: Big O(n) Because the loop has to run n times if we want to insert an element at the beginning of the array.

Insert at the end: Big O(n)

Insert in dynamic size array

Insert at the end. Let's see how dynamic size arrays work. In a dynamic size array, it pre-allocates some memory to n size. And when an element increases more than n it doubles its size and copies the n size array to a new 2n size array and deletes the n size array and does the insertion.

Did you find this article valuable?

Support aditya kumar by becoming a sponsor. Any amount is appreciated!