Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
1. Description of Merge Sort (No Coding)
Merge Sort is a divide-and-conquer sorting algorithm
that recursively splits an array into smaller subarrays, sorts them
individually, and then merges them back together in sorted order.
It is much faster than Bubble Sort, Selection Sort,
and Insertion Sort, especially for large datasets, because it runs in O(n
log n) time complexity in all cases. However, it requires additional memory
space of O(n).
Working Principle of Merge Sort
Visualization Example
Unsorted Array:
[8, 3, 5, 2, 9, 4, 1, 7]
Step 1: Divide the array into two halves
[8, 3, 5, 2] | [9, 4, 1, 7]
Step 2: Recursively divide further
[8, 3] | [5, 2] | [9, 4] | [1, 7]
Step 3: Recursively sort & merge back
Step 4: Merge sorted subarrays
Step 5: Merge final halves
2. Merge Sort Coding Examples
(a) Syllabus-Based Example (Sorting an array of numbers)
public
class MergeSortExample {
static void mergeSort(int arr[], int left,
int right) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
static void merge(int arr[], int left, int
mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int leftArray[] = new int[n1];
int rightArray[] = new int[n2];
for (int i = 0; i < n1; i++)
leftArray[i] = arr[left + i];
for (int j = 0; j < n2; j++)
rightArray[j] = arr[mid + 1 + j];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2)
{
if (leftArray[i] <=
rightArray[j]) {
arr[k] = leftArray[i];
i++;
} else {
arr[k] = rightArray[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = leftArray[i];
i++;
k++;
}
while (j < n2) {
arr[k] = rightArray[j];
j++;
k++;
}
}
public static void main(String args[]) {
int arr[] = {8, 3, 5, 2, 9, 4, 1, 7};
mergeSort(arr, 0, arr.length - 1);
System.out.println(java.util.Arrays.toString(arr));
}
}
Output:
[1, 2, 3, 4, 5, 7, 8, 9]
(b) Real-World Example (Sorting student names
alphabetically)
import
java.util.Arrays;
public
class MergeSortStrings {
static void mergeSort(String arr[], int
left, int right) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
static void merge(String arr[], int left,
int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
String leftArray[] = new String[n1];
String rightArray[] = new String[n2];
System.arraycopy(arr, left, leftArray,
0, n1);
System.arraycopy(arr, mid + 1,
rightArray, 0, n2);
int i = 0, j = 0, k = left;
while (i < n1 && j < n2)
{
if
(leftArray[i].compareTo(rightArray[j]) <= 0) {
arr[k] = leftArray[i];
i++;
} else {
arr[k] = rightArray[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = leftArray[i];
i++;
k++;
}
while (j < n2) {
arr[k] = rightArray[j];
j++;
k++;
}
}
public static void main(String args[]) {
String students[] =
{"Charlie", "Alice", "Bob", "David",
"Eve"};
mergeSort(students, 0, students.length
- 1);
System.out.println(Arrays.toString(students));
}
}
Output:
[Alice, Bob, Charlie, David, Eve]
3. Advantages of Merge Sort (Pros)
✔ Time complexity is O(n log
n) in all cases – Performs well on large datasets.
✔ Stable sorting algorithm – Maintains
relative order of duplicate values.
✔ Good for linked lists – Works well for
sorting linked lists due to efficient merging.
✔ Parallelizable – Can be efficiently
implemented using multithreading.
✔ Performs well on external sorting – Useful
for sorting large datasets stored on disk.
4. Disadvantages of Merge Sort (Cons)
❌ Requires extra memory of
O(n) – Uses additional space for merging.
❌
Not in-place sorting – Unlike Quick Sort, it needs extra arrays.
❌
More recursive function calls – Leads to overhead in memory.
❌
Slower than Quick Sort for random data – Quick Sort is usually faster in
practice.
❌
Not suitable for small arrays – Insertion Sort performs better for n
< 50.
5. How is Merge Sort Better Than Other Sorting
Techniques?
6. Best Cases to Use Merge Sort
✔ When sorting linked lists
– Efficient merging.
✔ When stability is required – Maintains order
of duplicates.
✔ For large datasets – Performs well on
large-scale sorting.
✔ For external sorting (e.g., files on disk) –
Handles large datasets efficiently.
7. Worst Cases to Use Merge Sort
❌ When memory usage is a
concern – Requires O(n) extra space.
❌
For small datasets – Insertion Sort is more efficient.
❌
When in-place sorting is required – Quick Sort is better in such cases.
Final Thoughts
Merge Sort is one of the most efficient sorting
algorithms, especially for large datasets. However, it requires extra
memory and is not as fast as Quick Sort for random data. 🚀
Bubble Sort repeatedly compares adjacent elements and swaps
them if they are in the wrong order. This leads to O(n²) time complexity,
making it highly inefficient for large datasets. The excessive number of swaps
and comparisons makes it slow compared to Merge Sort (O(n log n)) or Quick
Sort (O(n log n)).
Quick Sort is preferred in many scenarios because:
Insertion Sort is best for nearly sorted data
because:
A sorting algorithm is stable if it preserves the
relative order of elements with equal values.
Stable sorting algorithms in our list:
✅
Bubble Sort
✅
Insertion Sort
✅
Merge Sort
🚫
Selection Sort (can swap elements with the same value)
🚫
Quick Sort (depends on implementation)
Yes! We can optimize Bubble Sort by introducing a swap
flag:
Optimized Bubble Sort in Java:
static
void optimizedBubbleSort(int arr[]) {
int n = arr.length;
boolean swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
if (!swapped) break; // Stop if already sorted
}
}
This optimization improves performance significantly when
the input is partially sorted.
Quick Sort's worst-case occurs when:
To avoid this, randomized pivot selection or choosing
the median pivot is recommended.
Merge Sort is preferred for linked lists because:
Selection Sort is not stable because:
To make it stable, we can modify Selection Sort by
using linked lists or keeping track of indexes instead of swapping values
directly.
Merge Sort requires O(n) extra space because:
Optimizations to reduce space:
Yes, sorting can be done in O(n) time, but only for special
cases, such as:
These non-comparison sorts work by categorizing elements
into buckets instead of using comparisons (O(n log n) is the lower bound
for comparison-based sorts).
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)