
Domains
Agile Management
Master Agile methodologies for efficient and timely project delivery.
View All Agile Management Coursesicon-refresh-cwCertifications
Scrum Alliance
16 Hours
Best Seller
Certified ScrumMaster (CSM) CertificationScrum Alliance
16 Hours
Best Seller
Certified Scrum Product Owner (CSPO) CertificationScaled Agile
16 Hours
Trending
Leading SAFe 6.0 CertificationScrum.org
16 Hours
Professional Scrum Master (PSM) CertificationScaled Agile
16 Hours
SAFe 6.0 Scrum Master (SSM) CertificationAdvanced Certifications
Scaled Agile, Inc.
32 Hours
Recommended
Implementing SAFe 6.0 (SPC) CertificationScaled Agile, Inc.
24 Hours
SAFe 6.0 Release Train Engineer (RTE) CertificationScaled Agile, Inc.
16 Hours
Trending
SAFe® 6.0 Product Owner/Product Manager (POPM)IC Agile
24 Hours
ICP Agile Certified Coaching (ICP-ACC)Scrum.org
16 Hours
Professional Scrum Product Owner I (PSPO I) TrainingMasters
32 Hours
Trending
Agile Management Master's Program32 Hours
Agile Excellence Master's ProgramOn-Demand Courses
Agile and ScrumRoles
Scrum MasterTech Courses and Bootcamps
Full Stack Developer BootcampAccreditation Bodies
Scrum AllianceTop Resources
Scrum TutorialProject Management
Gain expert skills to lead projects to success and timely completion.
View All Project Management Coursesicon-standCertifications
PMI
36 Hours
Best Seller
Project Management Professional (PMP) CertificationAxelos
32 Hours
PRINCE2 Foundation & Practitioner CertificationAxelos
16 Hours
PRINCE2 Foundation CertificationAxelos
16 Hours
PRINCE2 Practitioner CertificationSkills
Change ManagementMasters
Job Oriented
45 Hours
Trending
Project Management Master's ProgramUniversity Programs
45 Hours
Trending
Project Management Master's ProgramOn-Demand Courses
PRINCE2 Practitioner CourseRoles
Project ManagerAccreditation Bodies
PMITop Resources
Theories of MotivationCloud Computing
Learn to harness the cloud to deliver computing resources efficiently.
View All Cloud Computing Coursesicon-cloud-snowingCertifications
AWS
32 Hours
Best Seller
AWS Certified Solutions Architect - AssociateAWS
32 Hours
AWS Cloud Practitioner CertificationAWS
24 Hours
AWS DevOps CertificationMicrosoft
16 Hours
Azure Fundamentals CertificationMicrosoft
24 Hours
Best Seller
Azure Administrator CertificationMicrosoft
45 Hours
Recommended
Azure Data Engineer CertificationMicrosoft
32 Hours
Azure Solution Architect CertificationMicrosoft
40 Hours
Azure DevOps CertificationAWS
24 Hours
Systems Operations on AWS Certification TrainingAWS
24 Hours
Developing on AWSMasters
Job Oriented
48 Hours
New
AWS Cloud Architect Masters ProgramBootcamps
Career Kickstarter
100 Hours
Trending
Cloud Engineer BootcampRoles
Cloud EngineerOn-Demand Courses
AWS Certified Developer Associate - Complete GuideAuthorized Partners of
AWSTop Resources
Scrum TutorialIT Service Management
Understand how to plan, design, and optimize IT services efficiently.
View All DevOps Coursesicon-git-commitCertifications
Axelos
16 Hours
Best Seller
ITIL 4 Foundation CertificationAxelos
16 Hours
ITIL Practitioner CertificationPeopleCert
16 Hours
ISO 14001 Foundation CertificationPeopleCert
16 Hours
ISO 20000 CertificationPeopleCert
24 Hours
ISO 27000 Foundation CertificationAxelos
24 Hours
ITIL 4 Specialist: Create, Deliver and Support TrainingAxelos
24 Hours
ITIL 4 Specialist: Drive Stakeholder Value TrainingAxelos
16 Hours
ITIL 4 Strategist Direct, Plan and Improve TrainingOn-Demand Courses
ITIL 4 Specialist: Create, Deliver and Support ExamTop Resources
ITIL Practice TestData Science
Unlock valuable insights from data with advanced analytics.
View All Data Science Coursesicon-dataBootcamps
Job Oriented
6 Months
Trending
Data Science BootcampJob Oriented
289 Hours
Data Engineer BootcampJob Oriented
6 Months
Data Analyst BootcampJob Oriented
288 Hours
New
AI Engineer BootcampSkills
Data Science with PythonRoles
Data ScientistOn-Demand Courses
Data Analysis Using ExcelTop Resources
Machine Learning TutorialDevOps
Automate and streamline the delivery of products and services.
View All DevOps Coursesicon-terminal-squareCertifications
DevOps Institute
16 Hours
Best Seller
DevOps Foundation CertificationCNCF
32 Hours
New
Certified Kubernetes AdministratorDevops Institute
16 Hours
Devops LeaderSkills
KubernetesRoles
DevOps EngineerOn-Demand Courses
CI/CD with Jenkins XGlobal Accreditations
DevOps InstituteTop Resources
Top DevOps ProjectsBI And Visualization
Understand how to transform data into actionable, measurable insights.
View All BI And Visualization Coursesicon-microscopeBI and Visualization Tools
Certification
24 Hours
Recommended
Tableau CertificationCertification
24 Hours
Data Visualization with Tableau CertificationMicrosoft
24 Hours
Best Seller
Microsoft Power BI CertificationTIBCO
36 Hours
TIBCO Spotfire TrainingCertification
30 Hours
Data Visualization with QlikView CertificationCertification
16 Hours
Sisense BI CertificationOn-Demand Courses
Data Visualization Using Tableau TrainingTop Resources
Python Data Viz LibsCyber Security
Understand how to protect data and systems from threats or disasters.
View All Cyber Security Coursesicon-refresh-cwCertifications
CompTIA
40 Hours
Best Seller
CompTIA Security+EC-Council
40 Hours
Certified Ethical Hacker (CEH v12) CertificationISACA
22 Hours
Certified Information Systems Auditor (CISA) CertificationISACA
40 Hours
Certified Information Security Manager (CISM) Certification(ISC)²
40 Hours
Certified Information Systems Security Professional (CISSP)(ISC)²
40 Hours
Certified Cloud Security Professional (CCSP) Certification16 Hours
Certified Information Privacy Professional - Europe (CIPP-E) CertificationISACA
16 Hours
COBIT5 Foundation16 Hours
Payment Card Industry Security Standards (PCI-DSS) CertificationOn-Demand Courses
CISSPTop Resources
Laptops for IT SecurityWeb Development
Learn to create user-friendly, fast, and dynamic web applications.
View All Web Development Coursesicon-codeBootcamps
Career Kickstarter
6 Months
Best Seller
Full-Stack Developer BootcampJob Oriented
3 Months
Best Seller
UI/UX Design BootcampEnterprise Recommended
6 Months
Java Full Stack Developer BootcampCareer Kickstarter
490+ Hours
Front-End Development BootcampCareer Accelerator
4 Months
Backend Development Bootcamp (Node JS)Skills
ReactOn-Demand Courses
Angular TrainingTop Resources
Top HTML ProjectsBlockchain
Understand how transactions and databases work in blockchain technology.
View All Blockchain Coursesicon-stop-squareBlockchain Certifications
40 Hours
Blockchain Professional Certification32 Hours
Blockchain Solutions Architect Certification32 Hours
Blockchain Security Engineer Certification24 Hours
Blockchain Quality Engineer Certification5+ Hours
Blockchain 101 CertificationOn-Demand Courses
NFT Essentials 101: A Beginner's GuideTop Resources
Blockchain Interview QsProgramming
Learn to code efficiently and design software that solves problems.
View All Programming Coursesicon-codeSkills
Python CertificationInterview Prep
Career Accelerator
3 Months
Software Engineer Interview PrepOn-Demand Courses
Data Structures and Algorithms with JavaScriptTop Resources
Python TutorialWeb Development
4.8 Rating 50 Questions 50 mins read6 Readers

The basic sorting method known as a bubble sort involves periodically switching nearby entries in an array. Because of its high average and worst-case temporal complexity, this is not appropriate for processing large amounts of data. Bubble sort tries to solve this by first comparing adjacent elements. If the element being compared is smaller than a given threshold value, the larger one is swapped with it and vice versa if the element being compared is larger than that threshold value. Thus samples are evaluated using less space than they used to be before the swap process started, hence making this algorithm faster than its variants such as heap sort or quick sort.
Implementation of bubble sort
Our example uses an unsorted array. Because bubble sort requires O(n2) time, we're making it concise and direct.

The first two items in a bubble sort are compared to see which one is bigger in the beginning.

Value 33 is bigger than 14, therefore, which is already in sorted places in this instance.

We now compare 33 with 27. Since 27 is less than 33, these two numbers must be switched.

The resulting array should seem as follows:

Let's next evaluate 33 and 35. These are already in ordered places, as we discover.

Afterward, we get to the further two values: 35 and 10.

However, we knew that 10 is less than 35. So they really aren't sorted as a result.

The values are switched. We discover that the array's end has been approached. The array shall seem as follows after the first iterative process:

We are specifically demonstrating the state of an array following each loop right now. After the second revision, it ought to resemble this:

Remember that at least a single value shifts at the end of every iteration.

Additionally, bubble sorts discover that an array is fully sorted when no switch is necessary. shown here

Program :
import java.util.Arrays;
public class BubbleSort
{
public static void main(String args[])
{
bubbleSort(new int[] { 20, 12, 45, 19, 91, 55 });
bubbleSort(new int[] { -1, 0, 1 });
bubbleSort(new int[] { -3, -9, -2, -1 });
}
public static void bubbleSort(int[] numbers)
{
System.out.printf("Unsorted array in Java :%s %n", Arrays.toString(numbers));
for (int i = 0; i < numbers.length; i++) {
for (int j = numbers.length -1; j > i; j--) {
if (numbers[j] < numbers[j - 1]) {
swap(numbers, j, j-1);
}
}
}
System.out.printf("Sorted Array using Bubble sort algorithm :%s %n", Arrays.toString(numbers));
}
public static void swap(int[] array, int from, int to){
int temp = array[from];
array[from] = array[to];
array[to] = temp;
}
}
Output:
Unsorted array in Java : [20, 12, 45, 19, 91, 55]
Sorted Array using Bubble sort algorithm : [12, 19, 20, 45, 55, 91]
Unsorted array in Java : [-1, 0, 1]
Sorted Array using Bubble sort algorithm : [-1, 0, 1]
Unsorted array in Java : [-3, -9, -2, -1]
Sorted Array using Bubble sort algorithm : [-9, -3, -2, -1]
A Divide and Conquer is an algorithm that splits the problem into smaller parts and solves them completely before combining the solutions. Merge Sort is a Divide and Conquer algorithm, which divides input arrays in two halves and merges these halves efficiently over a vector.
The divide-and-conquer approach is a problem-solving paradigm that addresses problems across different areas of expertise.
Implementation
Let's have a look at an array with the values arr[] = 38, 27, 43, 3, 9, 82, 10 to understand how merge sort works.
Firstly determine whether the array's left index is lower than its right index; if so, get the array's midway point.

However, since we already knew, until the atomic values are attained, merge sort consists of dividing arrays into equivalent parts repeatedly first.
In this, one could see that a 7-item array is split up into two arrays with sizes of 4 and 3, accordingly.

Find out once more if the left index for both arrays is lower than the right index, and if so, determine the centroid for both arrays once more.

Furthermore, keep dividing these two arrays into smaller and smaller parts until the array's atomic units are achieved, and more subdivision becomes impossible.

Begin combining the items once more, relying on comparisons of element sizes following dividing the array into the smallest units.
To integrate the elements from two lists into one, you must examine each list's elements first.

Following the final merger, the list appears as follows:

Program:
class MergeSort
{ void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } void sort(int arr[], int l, int r) { if (l < r) { int m = (l+r)/2; sort(arr, l, m); sort(arr , m+1, r); merge(arr, l, m, r); } } static void printArray(int arr[]) { int n = arr.length; for (int i=0; i<n; ++i) System.out.print(arr[i] + " "); System.out.println(); } public static void main(String args[]) { int arr[] = {12, 11, 13, 5, 6, 7}; System.out.println("Given Array is :"); printArray(arr); MergeSort ob = new MergeSort(); ob.sort(arr, 0, arr.length-1); System.out.println("\nSorted array is:"); printArray(arr); } }
Output:
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
Expect to come across this popular question in senior software engineer technical interview questions.
In the given problem, we need to count the occurrences of a given character in a string. In any programming language, this problem can have multiple solutions. Let's explain this problem a little bit further. There are numerous ways to determine the frequency of each letter, including Naive Approach, Counter Array, Java HashMap, and Java 8.
Here is a general working of a solution or, in more technical term, an algorithm for the problem
For this approach, we use the StringUtils class from the Spring framework, whose static method countOccurrenceOf(String, character) accepts a Text as input and a letter and outputs the character's frequency in that Text.
As an alternative, the Apache Commons StringUtils class for calculating the frequency of a letter in a sentence can be used to resolve this specific issue. To calculate the instances of a specific character or sub-string, use the countMatches() method of the Apache Commons StringUtils.
Program
import org.springframework.util.StringUtils; public class CountCharacters { public static void main(String args[]) { String input = "Today is Monday"; int count = StringUtils.countOccurrencesOf(input, "a"); System.out.println("count of occurrence of character 'a' on String: " + " Today is Monday' using Spring StringUtils " + count); int number = org.apache.commons.lang.StringUtils.countMatches(input, "a"); System.out.println("count of character 'a' on String: 'Today is Monday' using commons StringUtils " + number); int charCount = 0; for(int i =0 ; i<input.length(); i++){ if(input.charAt(i) == 'a'){ charCount++; } } System.out.println("count of character 'a' on String: 'Today is Monday' using for loop " + charCount); charCount = 0; //resetting character count for(char ch: input.toCharArray()){ if(ch == 'a'){ charCount++; } } System.out.println("count of character 'a' on String: 'Today is Monday' using for each loop " + charCount); } }
Output
count of occurrence of the character 'a' on String: 'Today is Monday' using Spring StringUtils 2
count of character 'a' on String: 'Today is Monday' using commons StringUtils 2
count of character 'a' on String: 'Today is Monday' using for loop 2
count of character 'a' on String: 'Today is Monday' using for each loop 2
Locating the very first non-repeated letter in a Sequence of String is a frequent programming exam question. But since the concept of strings is frequently covered in coding jobs, it is best to practice with very well topics like flipping strings with recursion or determining whether a string is a palindrome.
Dealing with all the non-repeated characters such as w, x, and y is a common problem in computational linguistics. Making a chart to hold the total of every character and selecting the very first entry that is unique will solve these issues.
Working
The solution above is implemented in the getFirstNonRepeatedChar(String str) method: The character array is looped through, and each element is compared to the index of the first non-repeated character. If there is a match, then that character's count will be stored in a hash table with its corresponding position as the key and that index as the value.
Since LinkedHashMap retains insertion order, next iterates through all the character arrays from start to finish in the following sequence to identify an item with value 1, which is your initial non-repeated character. First, it iterates through the remaining elements. Then it checks if the current character equals the value. If yes, then it concatenates the current character and repeated char. If not, then it returns a null value.
Program
import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class Programming { public static char getFirstNonRepeatedChar(String str) { Map<Character,Integer> counts = new LinkedHashMap<>(str.length()); for (char c : str.toCharArray()) { counts.put(c, counts.containsKey(c) ? counts.get(c) + 1 : 1); } for (Entry<Character,Integer> entry : counts.entrySet()) { if (entry.getValue() == 1) { return entry.getKey(); } } throw new RuntimeException("didn't find any non repeated Character"); } public static char firstNonRepeatingChar(String word) { Set<Character> repeating = new HashSet<>(); List<Character> nonRepeating = new ArrayList<>(); for (int i = 0; i < word.length(); i++) { char letter = word.charAt(i); if (repeating.contains(letter)) { continue; } if (nonRepeating.contains(letter)) { nonRepeating.remove((Character) letter); repeating.add(letter); } else { nonRepeating.add(letter); } } return nonRepeating.get(0); } public static char firstNonRepeatedCharacter(String word) { HashMap<Character,Integer> scoreboard = new HashMap<>(); for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if (scoreboard.containsKey(c)) { scoreboard.put(c, scoreboard.get(c) + 1); } else { scoreboard.put(c, 1); } } for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if (scoreboard.get(c) == 1) { return c; } } throw new RuntimeException("Undefined behavior"); } }
Output:
Enter the string: ssss
didn't find any non-repeated Character
Enter the string: missing
First non-repeating character is m
One of the fundamental Java duties is turning strings to integers and integers to strings, and most individuals learned about this while studying the Programming language. Provided that String and Integer are the most commonly applied types in all kinds of applications and you frequently get data between either of these types, even though String to Integer as well as Integer to String conversion is simple things at the same time, it was most helpful because of its regular necessity.
There are various methods for converting an int value to a string. If the last example of string conversion didn't suit you, here is one given below.
For this instance of turning an integer into a string, we utilized the static utility method String.valueOf(), which allows us to turn any integer variable into a string.
Since the String.valueOf() function is extended to handle practically every primitive type, you may utilize it to transform any other data type—including char, double, and float—into a String. Java uses static binding to invoke the appropriate method. Here is an example utilizing String.valueOf to convert an int to a string ()
Price as a string = Price.valueOf(123);
When the above line is executed, the integer 123 will be changed to the string "123".
Program
class GFG {
static int myAtoi(String str)
{
if (str == "" || str.matches("[a-zA-Z]+") || str.matches(".*[0-9].*")) {
return 0;
}
int res = 0;
for (int i = 0; i < str.length(); ++i)
res = res * 10 + str.charAt(i) - '0';
return res;
}
public static void main(String[] args)
{
String str = "8f9789";
// Function call
int val = myAtoi(str);
System.out.println(val);
}
}
Output:
String = 1234
Integer value = 1234
String = 123s
Invalid String
Integer value = 0
Firstly, before learning the difference between stable and unstable sorting algorithms, it's important to understand what a sorting algorithm is. In general, the sorting algorithm is the path that arranges the elements in the given list in a particular order which can lessen the complexity of the programme.
Now let's talk about stable and unstable sorting algorithms. So, a stable algorithm must maintain the values specified in the programme in the same order of the list to distinguish them from one another. At the same time, the list values in an unstable sorting algorithm do not keep the lexical order. When sorting a collection in an unstable manner, it is not crucial that the items remain constant across sorts.
Let's use an illustration to understand better:
Consider sorting the key-value pairs below in decreasing order of the keys:
INPUT: (4,2), (2,6), (1,3), (4,5), (6,1), (6,3)
There will be two distinct solutions or outputs for the given stack, and they are:
OUTPUT 1: (6,1), (6,3), (4,2), (4,5), (2,6), (1,3)
OUTPUT 2: (6,3), (6,1), (4,5), (4,2), (2,6), (1,3)
As you can see that (6,1) comes before (6,3) in the sorted order, in the same way, (4,2) comes before (4,5). So, the algorithm which will provide the 1st output is stable.
The 2nd output is produced with an unstable sorting algorithm, as the order of objects with the same key is not maintained in the sorted order. In this output (6,3) and (4,5) are listed before (6,1) and (4,2), which is not the case in the original given input.
A common question in technical interview questions for senior software engineers, don't miss this one.
DFS is the path used to find or search within the tree or any other graph structure.
DFS for a binary tree: When there is a given binary tree structure of the program, the DFS will search all the nodes from root to leaf from the left and then jump up to the right node and will go on until it finds a solution.
Let's understand this clearly with the help of this diagram:

In this diagram, 0 is the root node of the binary tree, while 1 and 2 are the children of the root node. Later, their children also have children( i.e., 1 has children, 3 and 4 while 5 and 6 are children of node 2).
But 3,4,5,6 don't have any children ahead so these are called leaves of the tree.
When the DFS algorithm is used for searching within the tree, it will first search from 0; then it will go on 1 and then to 3. After searching 3, it will move towards 4. Later it will jump up from 4 to 2 and then from 2 to 5. After that, it will search for 6.
One of the well-known algorithms for sorting the values in a given list is this quicksort. When compared to other sorting algorithms, this algorithm uses the "divide and gain" strategy to sort the data input, which renders it considerably faster in practice than others (i.e it divides the large array into two different smaller arrays which makes the sorting of values very quick within the given program). Either this algorithm is interactive, or it is recursive.
Implementation of quicksort algorithm:
Here's an example of the code to understand this algorithm completely:
import java.util.Arrays;
import java.util.Stack;
// A simple pair class in Java
class Pair
{
private final int x;
private final int y;
Pair(int x, int y)
{
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
}
class Main
{
public static void swap (int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static int partition(int a[], int start, int end)
{
// Pick the rightmost element as a pivot from the array
int pivot = a[end];
// elements less than the pivot will go to the left of `pIndex`
// elements more than the pivot will go to the right of `pIndex`
// equal elements can go either way
int pIndex = start;
// each time we find an element less than or equal to the pivot,
// `pIndex` is incremented, and that element would be placed
// before the pivot.
for (int i = start; i < end; i++)
{
if (a[i] <= pivot)
{
swap(a, i, pIndex);
pIndex++;
}
}
// swap `pIndex` with pivot
swap (a, pIndex, end);
// return `pIndex` (index of the pivot element)
return pIndex;
}
// Iterative Quicksort routine
public static void iterativeQuicksort(int[] a)
{
// create a stack for storing subarray start and end index
Stack<Pair> stack = new Stack<>();
// get the starting and ending index of the given array
int start = 0;
int end = a.length - 1;
// push the start and end index of the array into the stack
stack.push(new Pair(start, end));
// loop till stack is empty
while (!stack.empty())
{
// remove top pair from the list and get subarray starting
// and ending indices
start = stack.peek().getX();
end = stack.peek().getY();
stack.pop();
// rearrange elements across pivot
int pivot = partition(a, start, end);
// push subarray indices containing elements that are
// less than the current pivot to stack
if (pivot - 1 > start) {
stack.push(new Pair(start, pivot - 1));
}
// push subarray indices containing elements that are
// more than the current pivot to stack
if (pivot + 1 < end) {
stack.push(new Pair(pivot + 1, end));
}
}
}
// Iterative Implementation of Quicksort
public static void main(String[] args)
{
int a[] = { 9, -3, 5, 2, 6, 8, -6, 1, 3 };
iterativeQuicksort(a);
// print the sorted array
System.out.println(Arrays.toString(a));
}
} Output for this code will be:
[-6, -3, 1, 2, 3, 5, 6, 8, 9]
The insertion sort algorithm sorts the elements from the given stack by advancing the elements with a high rank toward the appropriate spot. Only one element is transferred at a time in this method.
Putting the insertion sort method into practice:
Let's look at an illustration to help you understand:
Insertion sort Function:
// Insertion Sort Functionvoid insertionSort(int array[], int n)
{
int i, element, j;
for (i = 1; i < n; i++) { element = array[i]; j = i - 1; /* Move elements of arr[0..i-1], that are greater than key by one position */ while (j >= 0 && array[j] > element) {
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = element;
}
} Insertion sort in C: code
#include <math.h>
#include <stdio.h>
// Insertion Sort Function
void insertionSort(int array[], int n)
{
int i, element, j;
for (i = 1; i < n; i++) { element = array[i]; j = i - 1; while (j >= 0 && array[j] > element) {
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = element;
}
}
// Function to print the elements of an array
void printArray(int array[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", array[i]);
printf("n");
} This algorithm also employs the divide and conquer approach to sort the entries in the list. Until there is just one element left in a given sub-list, it constantly divides the given list of elements into multiple sub-lists. Following that, these sublists are combined and sorted
Implementation of merge sort algorithm:
A[p..q], starting at p.
Until we reach the end of either L or M, pick the larger among the elements from L and M and place them in the correct position at A[p..q]
When we run out of elements in either L or M, pick up the remaining elements and put in A[p..q]
In code, this would look like:
// Merge two subarrays L and M into arr
void merge(int arr[], int p, int q, int r) {
// Create L ← A[p..q] and M ← A[q+1..r]
int n1 = q - p + 1;
int n2 = r - q;
int L[n1], M[n2];
for (int i = 0; i < n1; i++)
L[i] = arr[p + i];
for (int j = 0; j < n2; j++)
M[j] = arr[q + 1 + j];
// Maintain current index of sub-arrays and main array
int i, j, k;
i = 0;
j = 0;
k = p;
// Until we reach either end of either L or M, pick larger among
// elements L and M and place them in the correct position at A[p..r]
while (i < n1 && j < n2) {
if (L[i] <= M[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = M[j];
j++;
}
k++;
}
// When we run out of elements in either L or M,
// pick up the remaining elements and put in A[p..r]
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = M[j];
j++;
k++;
}
}