
									 Problem
								
								
									 Solution
								
								
									 Submissions
								
								
							Merge Sort
								Certification: Advanced Level
								Accuracy: 0%
								Submissions: 0
								Points: 15
							
							Write a C++ program that implements the merge sort algorithm. The program should take an unsorted array of integers and sort it in ascending order using the divide-and-conquer approach.
Example 1
- Input: array = [38, 27, 43, 3, 9, 82, 10]
- Output: [3, 9, 10, 27, 38, 43, 82]
- Explanation: 
  - Step 1: Divide the array into two halves
      - Left half: [38, 27, 43, 3]
- Right half: [9, 82, 10]
 
- Step 2: Recursively divide the left half
      - Left: [38, 27]
- Right: [43, 3]
 
- Step 3: Recursively divide until single elements
- Step 4: Merge back in sorted order
      - Merge [38] and [27] → [27, 38]
- Merge [43] and [3] → [3, 43]
- Merge [27, 38] and [3, 43] → [3, 27, 38, 43]
 
- Step 5: Similarly sort right half [9, 82, 10] → [9, 10, 82]
- Step 6: Merge [3, 27, 38, 43] and [9, 10, 82] → [3, 9, 10, 27, 38, 43, 82]
- Step 7: Return sorted array [3, 9, 10, 27, 38, 43, 82]
 
- Step 1: Divide the array into two halves
      
Example 2
- Input: array = [8, 4, 2, 1]
- Output: [1, 2, 4, 8]
- Explanation: 
  - Step 1: Divide the array into two halves
      - Left half: [8, 4]
- Right half: [2, 1]
 
- Step 2: Recursively divide until single elements
- Step 3: Merge back in sorted order
      - Merge [8] and [4] → [4, 8]
- Merge [2] and [1] → [1, 2]
 
- Step 4: Merge [4, 8] and [1, 2] → [1, 2, 4, 8]
- Step 5: Return sorted array [1, 2, 4, 8]
 
- Step 1: Divide the array into two halves
      
Constraints
- 1 ≤ array.length ≤ 10^5
- -10^6 ≤ array[i] ≤ 10^6
- Time Complexity: O(n log n), where n is the length of the array
- Space Complexity: O(n)
Editorial
									
												
My Submissions
										All Solutions
									| Lang | Status | Date | Code | 
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code | 
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Divide the unsorted array into two halves recursively until subarrays have just one element.
- Merge the sorted subarrays to produce new sorted subarrays until the entire array is sorted.
- Create a helper function to merge two sorted arrays.
- Use a temporary array to store merged elements.
- Compare elements from both subarrays and place them in the correct order in the temporary array.
