Merge Sort Algorithm in C++ | Visualization

The Merge Sort Algorithm is a sorting algorithm that uses the Divide and conquer technique to sort the array elements in ascending or descending order. In this algorithm, we break our problem into sub-problems then we try to merge the solution of the sub-problem to get the solution of our main problem. 


Working of Merge Sort Algorithm.

The merge Sort approach is entirely different than other sorting algorithms like Selection sort, Bubble sort, and Insertion sort where the time complexity of these algorithms is O(n^2) in the average case our Merge sort algorithm's time complexity is O(nlogn).


Here we divide the given unsorted array into two equal halves (if an array has an odd number of elements then one half will have more elements than the other half) then we apply some algorithm to sort these two equal halves and we merge these two halves in sorted order. 


Now if you observe carefully, we have two tasks one is to sort the two halves and the next is to merge the two sorted sub-array in a bigger array but in sorted order. We are going to use Recursion to perform this dividing of the array into two equal parts because we will keep on diving the array until no further division is possible and while returning back we are going to perform the merge operation.


Lets us first understand how the merge operation is going to take place when we already have two sorted sub-array. 

Let's say we named two sorted sub-array as the left sub-array (left[]), and the other as the right sub-array (right[]). Since all the elements of the given array, Arr[] are present either in the left sub-array or right sub-array so we will start picking the smallest element either from the left or right sub-array and start overwriting in the given Array Arr[]


.  

Algorithm to Merge Two-Sorted Arrays:

Step 1: Get the size of the left subarray and right subarray.

Step 2: Declare three variables i, j, and k, and initialize them with 0.

Step 3: Run a while loop with the below condition to merge two sorted arrays:

while(i < left_subarray_size && j < right_subarray_size){
        if(left[i] <= right[j]){
            arr[k] = left[i];
            k++;
            i++;
        }
        else{
            arr[k] = right[j];
            k++;
            j++;
        }
    }

Step 4: The above while loop condition will fail when we meet a condition where no elements are present to compare either in the left subarray or in the right subarray. In this case, we have picked all the elements of the other array and filled the rest of the position. We can run two different while loops for both left and right subarrays.

//copy the remaining elements from left subarray if any.
    while(i < left_subarray_size){
        arr[k] = left[i];
        i++;
        k++;
    }
    //copy the remaining elements from right subarray if any.
    while(j < right_subarray_size){
        arr[k] = right[j];
        j++;
        k++;
    }

Now after understanding the algorithm of merging two sorted arrays and combining them into a single larger sorted array. It is the right to understand the working of the Merge sort algorithm and then only you will understand why it was necessary to understand the above merging algorithm before. 

Basically, Merge Sort is a recursive algorithm in which we continually divide the given unsorted array into equal two parts until it cannot further divide. We will get this case when there is only one element left or the array is empty and it is our base case of recursion. When we hit the base case and start returning we will start merging both sorted halves into a larger array until the entire array is merged. This is where we will use the above algorithm of merging two sorted arrays. 


Steps to perform Merge Sort Algorithm.

Step 1: Call a recursive mergesort(arr[], l, r) with given array and one left variable and one right variable. 

Step 2: If left >= right then we hit the base case and you need to return.

Step 3: If left < right then we have need to perform the below task.

Step 4: Find the middle to divide the array into equal halves. 

  • mid = left + (right - left)/2

Step 5: Call mergersort again on first half.

  • mergesort(arr[], left, mid);

Step 6: Call mergersort again on second half.

  • mergesort(arr[], mid+1, right);

Step 7: Call merge function to merge two sorted half together (as shown above).

  • merge(arr[], left, mid, right);(alert-success)


C++ Code Implementation for Merge Sort Algorithm.

#include<iostream>
using namespace std;

//function to merge two sorted array
void merge(int arr[], int left, int mid, int right){
    
    int left_subarray_size = mid - left + 1;
    int right_subarray_size = right - mid;

    int leftArr[left_subarray_size];
    int rightArr[right_subarray_size];

    //copying data of left and right subarray from main array
    for(int i = 0; i < left_subarray_size; i++){
        leftArr[i] = arr[left+i];
    }
    for(int j = 0; j < right_subarray_size; j++){
        rightArr[j] = arr[mid+j+1];
    }

    int i = 0, j = 0, k = left;
    //Merging left and right sorted array into main array
    while(i < left_subarray_size && j < right_subarray_size){
        if(leftArr[i] <= rightArr[j]){
            arr[k] = leftArr[i];
            k++;
            i++;
        }
        else{
            arr[k] = rightArr[j];
            k++;
            j++;
        }
    }

    //copy the remaining elements from left subarray.
    while(i < left_subarray_size){
        arr[k] = leftArr[i];
        i++;
        k++;
    }
    //copy the remaining elements from right subarray.
    while(j < right_subarray_size){
        arr[k] = rightArr[j];
        j++;
        k++;
    }
}
//MergeSort Recursive Function
void mergeSort(int arr[], int left, int right){
   
    if(left >= right)
       return;
    
    int mid = left + (right - left)/2;   

    //Calling mergeSort recursively on both halves
    mergeSort(arr, left, mid);
    mergeSort(arr, mid+1, right);
    merge(arr, left, mid, right);
}
int main(){
    int arr[] = {2, 4, 1, 6, 8, 5, 3, 7};
    int n = sizeof(arr)/sizeof(arr[0]);

    cout<<"Array before Sorting: ";
    for(int i = 0; i < n; i++){
        cout<<arr[i]<<" ";
    }

    //Calling Merge Sort Function
    mergeSort(arr, 0, n-1);
    
    cout<<"\nArray after Sorting: ";
    for(int i = 0; i < n; i++){
        cout<<arr[i]<<" ";
    }
}
Output
Array before Sorting: 2 4 1 6 8 5 3 7
Array after Sorting: 1 2 3 4 5 6 7 8

  • Time complexity: O(NlogN)
  • Space Complexity: O(N)
In merge sort, extra space is required because we need to copy the given array into auxiliary space for sorting and it is a stable sorting algorithm. But merge sort is not a good choice for the smaller data units.

Insertion Sort Algorithm in C++.

The insertion Sort Algorithm is one of the simple (but not the best) sorting algorithms that is used to sort the array elements in ascending or descending order. In this article, we are going to understand the working and code implementation of this algorithm.


Insertion sort working is very similar to the way we sort playing cards in our hands. We assume that our first card is sorted and we will try to place our remaining unsorted cards in their correct position. In Insertion sort, an array is divided into sorted and unsorted parts and we have to take the elements from the unsorted part and place them in the sorted part of the array. This sorting algorithm is adaptive in nature and best for the data set which is partially sorted.

Working of Insertion Sort Algorithm.

Steps for Insertion Sort Algorithm.

Step 1: Run a loop to iterate all the elements of the array from 1 to n.


Step 2: Divide the given array into sorted and unsorted parts and assume that the first element is present in the sorted part of the array. 


Step 3: Pick the first element from the unsorted part of the array and compare it with elements present in the sorted part. 


Step 4: If you find all the elements present in the sorted part are smaller than the current element then include the current element into the sorted part and move to the next element, else find the correct position of the current element in the sorted part of the array and shift all the greater elements one unit right side to make space to insert the current element.


Step 5: Repeat the above steps until the entire array gets sorted. 


C++ Code Implementation for Insertion Sort Algorithm.

#include<iostream>
using namespace std;

//function for insertion sort
void insertionSort(int arr[], int n){
    int key, j;

    for(int i = 1; i < n; i++){
        key = arr[i];
        j = i-1;

        /*
        Moving the elements one position right
        that are greater than key to make space
        for key
        */
        while (j >= 0 && arr[j] > key)
        {
            arr[j+1] = arr[j];
            j = j-1;
        }
        arr[j+1] = key;
    }
}
int main(){
    int arr[] = {7, 2, 4, 1, 5, 3};
    //size of given array
    int n = sizeof(arr)/sizeof(arr[0]);

    insertionSort(arr, n);

    //Printing the sorted Array
    cout<<"Sorted Array: ";
    for(int i = 0; i < n; i++){
        cout<<arr[i]<<" ";
    }
}

Output:

Sorted Array: 1 2 3 4 5 7

  • Time Complexity: O(n^2)
  • Space Complexity: O(1)

Insertion sort is an in-place and stable sorting algorithm that works better than selection sort and bubble sort when the number of elements is small and partially sorted.  

How to Lock Google Chrome Incognito Mode with Fingerprint.

Lock Chrome Incognito mode with Fingerprint

Google Chrome is now providing an interesting feature of putting a Fingerprint lock on Incognito Mode whenever you exit the tabs. This feature is going to make Incognito mode safer and private for browsing by providing this extra layer of security. 


This is now only available on Andriod Google Chrome and it is very useful when you are in a situation of sharing your mobile with someone else. All Incognito tabs will automatically get locked as soon as you exit the tabs and when you try to reopen those tabs you will get one black screen with the "Unlock Incognito" button. You need to tap on that button and it will ask you for your fingerprint.


Steps to put Fingerprint Lock on Incognito Mode.

1. Open your Google Chrome Browser on your Android Device and type "chorme://flags".

Chorme Settings

2. You can see one search box on top, type "incognito-reauthentication-for-android". Once you get this option you need to select the drop-down menu and choose Enabled. Relaunch the Chrome Browser. 

Lock Incognito Mode

3. Click on the three dots in the upper right corner of Google Chrome and select "Settings".

Lock Chrome Incognito Mode with Fingerprint.

4. Inside the Settings option, you need to choose the "Privacy and Security" option.

Lock Incognito Mode with Fingerprint.

5. You need to enable the toggle option "Lock Incognito tabs when you leave Chrome" and Done.

Lock Chrome Incognito Mode with Fingerprint.

6. To unlock your locked tabs you need to click on "Unlock Incognito" on the screen and give your fingerprint.

Lock Google Chrome Incognito Mode with Fingerprint.

Now your Incognito mode is ready to use privately with biometric authentication security. This feature is not by default present in Chrome settings so do share this post with other people so they can also make use of this cool trick.

Bubble Sort Algorithm in C++.

The Bubble Sort is one of the popular and easy Sorting algorithms used to arrange the array of elements in ascending or descending order. In Bubble Sort Algorithm, we continuously keep on swapping two adjacent elements if they are present in the incorrect order. The worst-case time complexity of this algorithm is very high so it is not considered a suitable algorithm when there is a huge amount of data. 

Working of Bubble Sort Algorithm.


Steps for Bubble Sort Algorithm (Ascending Order):

  • Run two nested loops and traverse the given array where the outer loop will run n-1 times and the inner loop will run n-i-1 times.
  • In each iteration, we will pick two adjacent elements of the array and if arr[j] > arr[j+1] then we will swap their position else we will move to the next adjacent element. After completing each iteration the greatest element will move to the right end of the array.
  • In the end, you will see that no swapping is required and all elements are arranged in sorted order.

Below is the C++ Code Implementation of the Bubble Sort Algorithm.

#include<iostream>
using namespace std;

//Implementation of Bubble Sort
void bubbleSort(int arr[], int n){

    for(int i = 0; i < n-1; i++){
        for(int j = 0; j < n-i-1; j++){
            //Comparing two adjacent element
            if(arr[j] > arr[j+1]){
                swap(arr[j], arr[j+1]);
            }
        }
    }
}

int main(){
    int arr[] = {10, 23, 5, 8, 21, 15};
    //size of given array
    int n = sizeof(arr)/sizeof(arr[0]);

    bubbleSort(arr, n);

    cout<<"Sorted Array:";
    for(int i = 0; i < n; i++){
        cout<<arr[i]<<" ";
    }
}

Output:

Sorted Array:5 8 10 15 21 23

  • Time Complexity: O(n^2)
  • Space Complexity: O(1)

See more:

Selection Sort Algorithm in C++

The Selection Sort Algorithm is one of the popular sorting algorithms that is used to arrange the array of elements in sorted order either in ascending or descending order. 


In the selection sort algorithm (considering ascending order), we repeatedly find the smallest element from the unsorted part of the array and put them at the beginning. In every iteration, we divide the given array into a sorted and unsorted part and we move the smallest element from the unsorted part to the sorted part. 


Working of Selection Sort Algorithm.

Steps for Selection Sort Algorithm:

  • Initialize a min_index value with the initial index as 0.
  • Traverse the array to find the index of the minimum value of the given array. 
  • If any index value is smaller than min_index is found then we will swap both the value. It might be possible that more than one smaller value is present in that case you need to pick the smallest one only.
  • In the next iteration increment the min_index so it will point to the next value and then again start traversing the unsorted part (right-hand side of min_index) of the array to get the next smaller value.
  • Keep repeating the above steps until the entire array gets sorted. 

Below is the C++ Code Implementation for Selection Sort Algorithm.


//Program for Selection sort algorithm in C++
#include<iostream>
using namespace std;

void selectionSort(int arr[], int n){
    int min_index;

    //First loop keep on descreasing the size 
    //of unsorted array
    for(int i = 0; i < n-1; i++){
        min_index = i;
        //Second loop to find the smalles element
        //from unsorted subarray
        for(int j = i+1; j < n; j++){
            if(arr[j] < arr[min_index])
                min_index = j;
        }
        //swape the minimum element with ith element
        if(min_index != i)
            swap(arr[i], arr[min_index]);
    }
}

int main(){
    int arr[] = {10, 23, 5, 8, 21, 15};
    int n = sizeof(arr)/sizeof(arr[0]);

    selectionSort(arr, n);

    cout<<"Sorted Array:";
    for(int i = 0; i < n; i++){
        cout<<arr[i]<<" ";
    }
}

Output:

Sorted Array:5 8 10 15 21 23


Time Complexity: The Time complexity of the Selection Sort Algorithm is O(n^2) as we are using two nested loops one is for selecting the current minimum element and the next loop is to find the minimum element out of the remaining unsorted array. 

Space Complexity: The Space complexity of the Selection sort is O(1) as we are not using any extra space for storing any kind of value except min_index and two swapping values.


See more:

(getButton) #text=(Insertion Sort Algorithm) #icon=(link) #color=(#2339bd)

(getButton) #text=(Bubble Sort Algorithm) #icon=(link) #color=(#2339bd)

(getButton) #text=(Merge Sort Algorithm) #icon=(link) #color=(#2339bd)

(getButton) #text=(Quick Sort Algorithm) #icon=(link) #color=(#2339bd)

Array Data Structure in C/C++

An Array is a linear Data Structure that contains a number of data values of the same type stored at contiguous memory locations. 


Before you start learning more about Array you must know about Data Structure. Data Structure is a way of organizing and storing data and each data structure is designed to organize data to suit a specific purpose. 


Below is the example of Array Data Structure which we can visualize as a large chunk of memory divided into a smaller block of memory of equal size and each block is capable of storing a data value of same type.

Array Data Structure

In the above example, you can observe that we can have different kinds of Array Data Structure like Integer Array or Character Array based on the type of value we are storing in it. All the elements of an array are arranged in a sequential manner you can access any element of an array using the index value like a[4] = 21. This is an example of a one-dimensional Array.


Now as you know what a one-dimensional array looks like, let's understand,


How to Declare and Define One-Dimensional Array?

The syntax of declaring a 1D array is like first of all you have to define the data type of the array then the name of the array and the number of elements you want to store in this array.

Syntax: data_type name of the array[no. of elements];

Example: int arr [5];

Here you are not only declaring the array you are also defining the array by providing the detail of the number of elements you want to store because based on this compiler will allocate a contiguous block of memory of size  = 5*sizeof(int) where the size of an integer depends on machines.

Note: The length of an array can be specified by any positive integer constant expression and specifying the length of an array using a macro is considered to be an excellent practice so that if there is any change in array size you don't need to update it everywhere. 

#define N 15

int arr[N];(alert-success)

How to Access the One-Dimensional Array elements?

To access any array element, you just need to specify the array name with the index value of that particular element in the square bracket. Usually, most of the time we use 0-based indexing so if the size of the array is declared as 5 then the last element is going to be present at index 4 (length -1) and the first element is going to be present at index 0.

Syntax: array_name[index];

Example: 
Accessing the last element of the array: arr[4];
Accessing the first element of the array: arr[0];


How to initialize One Dimensional Array?

There are multiple methods of initializing a 1D array here we are going to see four different methods. 


Method 1: In this, you have declared the data type and size of the array and you can initialize the array element inside curly brackets and the number of elements present inside the bracket should be equal to the size of the array.

int arr[5] = {3, 5, 6, 9, 12};


Method 2: In this, you don't need to declare the array size in advance you can directly initialize the array elements inside curly brackets, and based on the number of elements present you can calculate the size of the array.

int arr[] = {3, 5, 6, 9, 12};


Method 3: In this, you first declare the array with the number of elements you want to store in that array, and then using the index value you can initialize the element one by one.

int arr[5];

arr[0] = 3;
arr[1] = 5;
arr[2] = 6;
arr[3] = 9;
arr[4] = 12;


Method 4: In this, you first declare the array with the number of elements you want to store, and then you run a for-loop and take the element as input from the user and which will then initialize inside the array one by one.

int arr[5];

for(int i = 0; i < 5; i++){
   cin >> arr[i];
}


Note: If the number of elements you initialize is lesser than the length of the array then in that case the remaining locations of the array are filled by value 0. But make sure that must have to specify at least 1 element for this. It cannot be completely empty and it is also not allowed to add more elements than the length of an array.

int arr[10] = {5, 7, 9, 11, 5, 21};

All the remaining elements of array will automatically fill by 0
int arr[10] = {5, 7, 9, 11, 5, 21, 0, 0, 0, 0};


You can use the sizeof() operator to find the number of elements present in an Array. Below is the syntax for calculating this. 

int num = sizeof(name_of_array)/sizeof(name_of_array[0])


C++ Program to Print One-Dimensional Array

#include<iostream>
using namespace std;

int main(){
    //Initialising 1D Array
    int arr[] = {3, 5, 9, 11, 2, -1, 20};
    //No. of elements present in the array
    int n = sizeof(arr)/sizeof(arr[0]);

    //Printing all array elememts
    for(int i = 0; i < n; i++){
        cout<<arr[i]<<" ";
    }
}

Output:

3 5 9 11 2 -1 20


Multidimensional Arrays in C/C++.

A Multidimensional Array can be defined as an Array of Arrays that store data values of the same type in a tabular form. The size (number of elements it can store) of a multidimensional array can be calculated by multiplying the size of all the dimensions. 

The general form of declaring an N-dimensional Array is as  follows:

syntax: data_type name_of_array[size1][size2]...[sizeN];

For example:
int arr[4][5]     //Two Dimensional Array
size of arr[4][5] = 4x5 = 20 elements we can store in this array

int arr[4][5][6]  //Three Dimensional Array
size of arr[4][5][6] = 4x5x6 = 120 elements we can store in this array


Two Dimensional Array


Two-Dimensional Array.

A two-Dimensional Array can be visualized as a matrix (or table) which can be represented with n number of rows and m number of columns. The elements which are going to be present in a 2D Array must be of the same data type. Below is the syntax for the declaration of a 2D Array.
syntax: data_type name_of_array[no. of rows][no. of columns];
Example: int arr[4][3];

How To Initialize a Two-Dimensional Array?

There are multiple ways of initializing a 2D Array and we are going to see two different methods out of all:
Method 1: int arr[4][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
Method 2: int arr[4][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};

We can access elements stored in a 2D Array by using the row index and column index of that particular element in the matrix.

C++ Program to Print Two-Dimensional Array.

#include<iostream>
using namespace std;

int main(){
    //Initialising 1D Array
    int arr[4][3] = {{3, 15, 9}, {2, 11, -1}, {7, 10, 4},{0, 1, 21}};    

    //Printing all array elements
    for(int i = 0; i < 4; i++){
        for(int j = 0; j < 3; j++){
            cout<< arr[i][j]<<" ";
        }
        cout<<"\n";
    }
}

Output:

3 15 9 
2 11 -1
7 10 4
0 1 21


I hope you have understood the basic and fundamental building blocks of Array Data Structure. If you have any questions regarding this topic please write them in the comment section below. 


👉Support Us by Sharing our post with others if you really found this useful and also share your valuable feedback in the comment section below so we can work on them and provide you best ðŸ˜Š.(alert-success) 

Program to Find the K-Beauty of a Number.

Given an integer num and K, we have to count the number of K-beauty substrings possible for the given integer num. There are two conditions that need to be satisfied by the substring to become K-beauty.

  • The substring must be of length K.
  • The integer form of substring is a divisor of given integer num.

 Note: Leading zeros are allowed in the substrings and 0 is not a divisor of any integer value.

Example 1:

Input: num = 360, K = 2
Output: 2

Explanation: Consider the given integer as a string.

"36" is a substring of  "360" and 36 is a divisor of 360.
"60" is a substring of  "360" and 60 is a divisor of 360.

Count of K-beauty possible = 2

Example 2:

Input: num = 540540, K = 3
Output: 3

Explanation: Consider the given integer as a string.

"540" is a substring of  "540540" and 540 is a divisor of 540540.
"405" is a substring of  "540540" and 405 is not a divisor of 540540.
"054" is a substring of  "540540" and 054 is a divisor of 540540.
"540" is a substring of  "540540" and 540 is a divisor of 540540.

Count of K-beauty possible = 3


Approach 1: Fixed-Sized Sliding Window.

This question can be easily solved using the fixed-sized sliding window technique as our window size K is already given in the question.

  • Convert the given num integer to a string using the to_string(num) property in C++.
  • Initialize the i and j pointers with 0 to calculate the size of our sliding window and one count variable to get the count of K-beauty.
  • Run a while loop for our string size and keep on increasing our window size until our window size become equal to K. (j-i+1 == K)
  • Extract the string using the substring function and convert that string to an integer n.
  • Check whether the converted number n is a divisor of given integer num. If Yes, then increase the count.
  • Return the count as an output.

C++ Code for finding the K-beauty of a number:

#include<iostream>
#include <string>
using namespace std;

int KBeautyCount(int num, int K){
    //convert the given num to string
    string str = to_string(num);
    //initialize i and j for window size
    int i = 0, j = 0, count = 0;

    while(j < str.size()){
        if(j-i+1 < K){
            //increment the j to get window size
            j++;
        }
        else if(j-i+1 == K){
            //get the substring and convert it to integer
            string s = str.substr(i, K);
            int n = stoi(s);
            //check if n is divisor of num 
            if(n != 0 && num % n == 0){
                count++;
            }
            i++;
            j++;
        }
    }
    return count;
}
int main(){
    int num = 540540;
    int K = 3;
    cout<<KBeautyCount(num, K);
}

Output:

3

  • Time Complexity: O(n)
  • Space Complexity: O(1)
Approach 2: Using a single for loop and substring property.

In this very easy and brute force approach, we just need to run a for loop and extra the substring of size K and then convert that substring into an integer and check whether the given condition is satisfied by that integer or not. Similarly, check the condition for all possible substrings of size K.

C++ Code for finding the K-beauty of a number:

#include<iostream>
#include <string>
using namespace std;

int KBeautyCount(int num, int K){
    //convert the given num to string
    string str = to_string(num);
    //Size of String
    int n = str.size();
    int count = 0;

    for(int i = 0; i < n-K+1; i++){
        //extract the substring of size K
        string s = str.substr(i,K);
        //convert the string to integer
        int snum = stoi(s);
        if(snum != 0 && num % snum == 0){
            count++;
        }
    }
    return count;
}
int main(){
    int num = 540540;
    int K = 3;
    cout<<KBeautyCount(num, K);
}

Output:

3
  • Time Complexity: O(n)
  • Space Complexity: O(1)
👉Support Us by Sharing our post with others if you really found this useful and also share your valuable feedback in the comment section below so we can work on them and provide you best ðŸ˜Š.(alert-success) 

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by AlgoLesson