Sort an array when two halves are sorted
Last Updated :
23 Jul, 2025
Given an integer array arr[] whose first k elements and remaining n–k elements (for any 0 ≤ k ≤ n) are each sorted, merge these two sorted halves into a single fully sorted array.
Note : There doesn't exists more than two sorted halves in an array.
Examples:
Input : arr[] = [2, 3, 8, -1, 7, 10]
Output : [-1, 2, 3, 7, 8, 10]
Explanation : First and last three sorted elements are [2, 3, 8] and [-1, 7, 10], after merging both halves we get a final sorted array.
Input : arr[] = [-4, 6, 9, -1, 3]
Output : [-4, -1, 3, 6, 9]
Explanation : First three and last two sorted elements are [-4, 6, 9] and [-1, 3], after merging both halves we get a final sorted array.
[Naive Approach] Sort the array
The main logic is to sort the array using built in functions (generally an implementation of quick sort). This approach ignores the “two halves” and simply calls the language’s built‑in sort to sort the entire array.
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> mergeHalves(vector<int> &arr){
// Sort the given array using sort STL
sort(arr.begin(), arr.end());
return arr;
}
int main(){
vector<int> arr = {2, 3, 8, -1, 7, 10};
int n = arr.size();
mergeHalves(arr);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;
public class GFG {
public static ArrayList<Integer> mergeHalves(int[] arr) {
// Sort the given array using Arrays.sort
Arrays.sort(arr);
//Build and return an ArrayList from the sorted array
ArrayList<Integer> result = new ArrayList<>(arr.length);
for (int x : arr) {
result.add(x);
}
return result;
}
public static void main(String[] args) {
int[] arr = {2, 3, 8, -1, 7, 10};
int n = arr.length;
ArrayList<Integer> ans = mergeHalves(arr);
for (int i = 0; i < n; i++) {
System.out.print(ans.get(i) + " ");
}
}
}
Python
def mergeHalves(arr):
# Sort the given list using list.sort()
arr.sort()
return arr
if __name__ == "__main__":
arr = [2, 3, 8, -1, 7, 10]
n = len(arr)
mergeHalves(arr)
for i in range(n):
print(arr[i], end=" ")
C#
using System;
using System.Collections.Generic;
class GFG {
static List<int> mergeHalves(int[] arr) {
// Sort the given array using Array.Sort()
Array.Sort(arr);
List<int> result = new List<int>(arr.Length);
foreach (int x in arr) {
result.Add(x);
}
return result;
}
static void Main() {
int[] arr = { 2, 3, 8, -1, 7, 10 };
int n = arr.Length;
List<int> ans = mergeHalves(arr);
for (int i = 0; i < n; i++)
Console.Write(ans[i] + " ");
}
}
JavaScript
function mergeHalves(arr) {
// Sort the given array using Array.prototype.sort
arr.sort((a, b) => a - b);
return arr;
}
// Driver Code
const arr = [2, 3, 8, -1, 7, 10];
const n = arr.length;
mergeHalves(arr);
for (let i = 0; i < n; i++)
process.stdout.write(arr[i] + " ");
PHP
<?php
function mergeHalves(&$arr) {
// Sort the given array using sort()
sort($arr);
return $arr;
}
$arr = [2, 3, 8, -1, 7, 10];
$n = count($arr);
mergeHalves($arr);
for ($i = 0; $i < $n; $i++) {
echo $arr[$i] . " ";
}
Time Complexity : O(n(log(n)))
Auxiliary Space : O(log(n))
Note :- For Java, Python and C# the Space Complexity will be O(n)
[Expected Approach] Using merge sort - O(n) Time and O(n) Space
The main idea behind this approachis to use an auxiliary array which is very similar to the Merge Function of Merge sort. Find where the first sorted part ends, then walk through both parts side by side, always picking the smaller next number to build the fully sorted list.
C++
#include <iostream>
#include <vector>
using namespace std;
vector<int> mergeHalves(vector<int> &arr){
int n = arr.size();
// starting index of second half
int index = 0;
// Temp Array store sorted resultant array
vector<int> temp(n);
// First Find the point where array is divided
// into two half
for (int i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1]) {
index = i + 1;
break;
}
}
// If Given array is all-ready sorted
if (index == 0)
return arr;
// Merge two sorted arrays in single sorted array
int i = 0, j = index, k = 0;
while (i < index && j < n) {
if (arr[i] < arr[j])
temp[k++] = arr[i++];
else
temp[k++] = arr[j++];
}
// Copy the remaining elements of arr[i to index ]
while (i < index)
temp[k++] = arr[i++];
// Copy the remaining elements of arr[index to n ]
while (j < n)
temp[k++] = arr[j++];
return temp;
}
int main(){
vector<int> arr = {2, 3, 8, -1, 7, 10};
int n = arr.size();
vector<int> ans(n);
ans = mergeHalves(arr);
for (int i = 0; i < n; i++)
cout << ans[i] << " ";
return 0;
}
Java
import java.util.ArrayList;
class GFG {
public static ArrayList<Integer> mergeHalves(int[] arr) {
int n = arr.length;
// starting index of second half
int index= 0;
// Temp Array store sorted resultant array
ArrayList<Integer> temp = new ArrayList<>();
for (int i = 0; i < n; i++) temp.add(0);
// First Find the point where array is divided
// into two half
for (int i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1]) {
index = i + 1;
break;
}
}
// If Given array is all-ready sorted
if (index == 0) {
ArrayList<Integer> original = new ArrayList<>();
for (int x : arr) original.add(x);
return original;
}
// Merge two sorted arrays in single sorted array
int i = 0, j = index, k = 0;
while (i < index && j < n) {
if (arr[i] < arr[j])
temp.set(k++, arr[i++]);
else
temp.set(k++, arr[j++]);
}
// Copy the remaining elements of arr[i to index ]
while (i < index)
temp.set(k++, arr[i++]);
// Copy the remaining elements of arr[index to n ]
while (j < n)
temp.set(k++, arr[j++]);
return temp;
}
public static void main(String[] args) {
int[] arr = {2, 3, 8, -1, 7, 10};
int n = arr.length;
ArrayList<Integer> ans = mergeHalves(arr);
for (int i = 0; i < n; i++)
System.out.print(ans.get(i) + " ");
}
}
Python
def mergeHalves(arr):
n = len(arr)
# starting index of second half
index = 0
# Temp Array store sorted resultant array
temp = [0] * n
# First Find the point where array is divided
# into two half
for i in range(n - 1):
if arr[i] > arr[i + 1]:
index = i + 1
break
# If Given array is all-ready sorted
if index == 0:
return arr.copy()
# Merge two sorted arrays in single sorted array
i, j, k = 0, index, 0
while i < index and j < n:
if arr[i] < arr[j]:
temp[k] = arr[i]
i += 1
else:
temp[k] = arr[j]
j += 1
k += 1
# Copy the remaining elements of arr[i to index]
while i < index:
temp[k] = arr[i]
i += 1
k += 1
# Copy the remaining elements of arr[index to n ]
while j < n:
temp[k] = arr[j]
j += 1
k += 1
return temp
if __name__ == "__main__":
arr = [2, 3, 8, -1, 7, 10]
n = len(arr)
ans = mergeHalves(arr)
for i in range(n):
print(ans[i], end=" ")
C#
using System;
using System.Collections.Generic;
public class GFG {
public static List<int> mergeHalves(int[] arr) {
int n = arr.Length;
// starting index of second half
int index = 0;
// Temp Array store sorted resultant array
List<int> temp = new List<int>(new int[n]);
// First Find the point where array is divided
// into two half
for (int i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1]) {
index = i + 1;
break;
}
}
// If Given array is all-ready sorted
if (index == 0) {
// copy original array into a List to return
List<int> original = new List<int>();
foreach (int x in arr) original.Add(x);
return original;
}
// Merge two sorted arrays in single sorted array
int i1 = 0, j = index, k = 0;
while (i1 < index && j < n) {
if (arr[i1] < arr[j])
temp[k++] = arr[i1++];
else
temp[k++] = arr[j++];
}
// Copy the remaining elements of arr[i to index ]
while (i1 < index)
temp[k++] = arr[i1++];
// Copy the remaining elements of arr[ index to n ]
while (j < n)
temp[k++] = arr[j++];
return temp;
}
public static void Main() {
int[] arr = {2, 3, 8, -1, 7, 10};
int n = arr.Length;
List<int> ans = mergeHalves(arr);
for (int i = 0; i < n; i++)
Console.Write(ans[i] + " ");
}
}
JavaScript
function mergeHalves(arr) {
let n = arr.length;
// starting index of second half
let index = 0;
// Temp Array store sorted resultant array
let temp = new Array(n).fill(0);
// First Find the point where array is divided
// into two half
for (let i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1]) {
index = i + 1;
break;
}
}
// If Given array is all-ready sorted
if (index === 0)
return arr.slice(); // return a shallow copy
// Merge two sorted arrays in single sorted array
let i = 0, j = index, k = 0;
while (i < index && j < n) {
if (arr[i] < arr[j])
temp[k++] = arr[i++];
else
temp[k++] = arr[j++];
}
// Copy the remaining elements of arr[i to index ]
while (i < index)
temp[k++] = arr[i++];
// Copy the remaining elements of arr[ index to n ]
while (j < n)
temp[k++] = arr[j++];
return temp;
}
// Driver Code
let arr = [2, 3, 8, -1, 7, 10];
let n = arr.length;
let ans = mergeHalves(arr);
for (let i = 0; i < n; i++)
process.stdout.write(ans[i] + " ");
Similar Reads
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to Sorting Techniques Sorting refers to rearrangement of a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure.Why Sorting Algorithms are ImportantSorting algorithms are essential in Comput
15+ min read
Most Common Sorting Algorithms
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
12 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Heap Sort - Data Structures and Algorithms Tutorials Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
14 min read
Counting Sort - Data Structures and Algorithms Tutorials Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
7 min read