Sort an array when two halves are sorted
Last Updated :
23 Jun, 2023
Given an integer array of which both first half and second half are sorted. Task is to merge two sorted halves of array into single sorted array.
Examples:
Input : A[] = { 2, 3, 8, -1, 7, 10 }
Output : -1, 2, 3, 7, 8, 10
Input : A[] = {-4, 6, 9, -1, 3 }
Output : -4, -1, 3, 6, 9
Method 1: A Simple Solution is to sort the array using built in functions (generally an implementation of quick sort).
Below is the implementation of above method:
C++
// C++ program to Merge two sorted halves of
// array Into Single Sorted Array
#include <bits/stdc++.h>
using namespace std;
void mergeTwoHalf(int A[], int n)
{
// Sort the given array using sort STL
sort(A, A + n);
}
// Driver code
int main()
{
int A[] = { 2, 3, 8, -1, 7, 10 };
int n = sizeof(A) / sizeof(A[0]);
mergeTwoHalf(A, n);
// Print sorted Array
for (int i = 0; i < n; i++)
cout << A[i] << " ";
return 0;
}
Java
// Java program to Merge two sorted halves of
// array Into Single Sorted Array
import java.io.*;
import java.util.*;
class GFG {
static void mergeTwoHalf(int[] A, int n)
{
// Sort the given array using sort STL
Arrays.sort(A);
}
// Driver code
static public void main(String[] args)
{
int[] A = { 2, 3, 8, -1, 7, 10 };
int n = A.length;
mergeTwoHalf(A, n);
// Print sorted Array
for (int i = 0; i < n; i++)
System.out.print(A[i] + " ");
}
}
// This code is contributed by vt_m .
Python3
# Python program to Merge two sorted
# halves of array Into Single Sorted Array
def mergeTwoHalf(A, n):
# Sort the given array using sort STL
A.sort()
# Driver Code
if __name__ == '__main__':
A = [2, 3, 8, -1, 7, 10]
n = len(A)
mergeTwoHalf(A, n)
# Print sorted Array
for i in range(n):
print(A[i], end=" ")
# This code is contributed by 29AjayKumar
C#
// C# program to Merge two sorted halves of
// array Into Single Sorted Array
using System;
class GFG {
static void mergeTwoHalf(int[] A, int n)
{
// Sort the given array using sort STL
Array.Sort(A);
}
// Driver code
static public void Main()
{
int[] A = { 2, 3, 8, -1, 7, 10 };
int n = A.Length;
mergeTwoHalf(A, n);
// Print sorted Array
for (int i = 0; i < n; i++)
Console.Write(A[i] + " ");
}
}
// This code is contributed by vt_m .
PHP
<?php
// PHP program to Merge two sorted halves
// of array Into Single Sorted Array
function mergeTwoHalf(&$A, $n)
{
// Sort the given array using sort STL
sort($A, 0);
}
// Driver Code
$A = array(2, 3, 8, -1, 7, 10);
$n = sizeof($A);
mergeTwoHalf($A, $n);
// Print sorted Array
for ($i = 0; $i < $n; $i++)
echo $A[$i] . " ";
// This code is contributed
// by Akanksha Rai
?>
JavaScript
<script>
// Javascript program to Merge two sorted halves of
// array Into Single Sorted Array
function mergeTwoHalf(A, n)
{
// Sort the given array using sort function
A.sort((a,b) => a-b);
}
// Driver code
var A = [ 2, 3, 8, -1, 7, 10 ];
var n = A.length;
mergeTwoHalf(A, n);
// Print sorted Array
for (var i = 0; i < n; i++)
document.write( A[i] + " ");
// This code is contributed by itsok.
</script>
Time Complexity: O(n*log(n)) best & average case, O(n^2) worst case (for quicksort)
Space Complexity: O(log(n)) to O(n) depending on the case & implementation (for quicksort)
For more details, check out the GFG article on Quicksort.
Method 2: A more efficient solution is to use an auxiliary array which is very similar to the Merge Function of Merge sort.
Below is the implementation of above approach :
C++
// C++ program to Merge Two Sorted Halves Of
// Array Into Single Sorted Array
#include <bits/stdc++.h>
using namespace std;
// Merge two sorted halves of Array into single
// sorted array
void mergeTwoHalf(int A[], int n)
{
int half_i = 0; // starting index of second half
// Temp Array store sorted resultant array
int temp[n];
// First Find the point where array is divide
// into two half
for (int i = 0; i < n - 1; i++) {
if (A[i] > A[i + 1]) {
half_i = i + 1;
break;
}
}
// If Given array is all-ready sorted
if (half_i == 0)
return;
// Merge two sorted arrays in single sorted array
int i = 0, j = half_i, k = 0;
while (i < half_i && j < n) {
if (A[i] < A[j])
temp[k++] = A[i++];
else
temp[k++] = A[j++];
}
// Copy the remaining elements of A[i to half_! ]
while (i < half_i)
temp[k++] = A[i++];
// Copy the remaining elements of A[ half_! to n ]
while (j < n)
temp[k++] = A[j++];
for (int i = 0; i < n; i++)
A[i] = temp[i];
}
// Driver code
int main()
{
int A[] = { 2, 3, 8, -1, 7, 10 };
int n = sizeof(A) / sizeof(A[0]);
mergeTwoHalf(A, n);
// Print sorted Array
for (int i = 0; i < n; i++)
cout << A[i] << " ";
return 0;
}
Java
// Java program to Merge Two Sorted Halves Of
// Array Into Single Sorted Array
import java.io.*;
class GFG {
// Merge two sorted halves of Array
// into single sorted array
static void mergeTwoHalf(int[] A, int n)
{
int half_i = 0; // starting index of second half
int i;
// Temp Array store sorted resultant array
int[] temp = new int[n];
// First Find the point where array is divide
// into two half
for (i = 0; i < n - 1; i++) {
if (A[i] > A[i + 1]) {
half_i = i + 1;
break;
}
}
// If Given array is all-ready sorted
if (half_i == 0)
return;
// Merge two sorted arrays in single sorted array
i = 0;
int j = half_i;
int k = 0;
while (i < half_i && j < n) {
if (A[i] < A[j])
temp[k++] = A[i++];
else
temp[k++] = A[j++];
}
// Copy the remaining elements of A[i to half_! ]
while (i < half_i)
temp[k++] = A[i++];
// Copy the remaining elements of A[ half_! to n ]
while (j < n)
temp[k++] = A[j++];
for (i = 0; i < n; i++)
A[i] = temp[i];
}
// Driver code
static public void main(String[] args)
{
int[] A = { 2, 3, 8, -1, 7, 10 };
int n = A.length;
mergeTwoHalf(A, n);
// Print sorted Array
for (int i = 0; i < n; i++)
System.out.print(A[i] + " ");
}
}
// This code is contributed by vt_m .
Python3
# Python3 program to Merge Two Sorted Halves Of
# Array Into Single Sorted Array
# Merge two sorted halves of Array into single
# sorted array
def mergeTwoHalf(A, n):
# Starting index of second half
half_i = 0
# Temp Array store sorted resultant array
temp = [0 for i in range(n)]
# First Find the point where array is
# divide into two half
for i in range(n - 1):
if (A[i] > A[i + 1]):
half_i = i + 1
break
# If Given array is all-ready sorted
if (half_i == 0):
return
# Merge two sorted arrays in single
# sorted array
i = 0
j = half_i
k = 0
while (i < half_i and j < n):
if (A[i] < A[j]):
temp[k] = A[i]
k += 1
i += 1
else:
temp[k] = A[j]
k += 1
j += 1
# Copy the remaining elements of A[i to half_! ]
while i < half_i:
temp[k] = A[i]
k += 1
i += 1
# Copy the remaining elements of A[ half_! to n ]
while (j < n):
temp[k] = A[j]
k += 1
j += 1
for i in range(n):
A[i] = temp[i]
# Driver code
A = [ 2, 3, 8, -1, 7, 10 ]
n = len(A)
mergeTwoHalf(A, n)
# Print sorted Array
print(*A, sep = ' ')
# This code is contributed by avanitrachhadiya2155
C#
// C# program to Merge Two Sorted Halves Of
// Array Into Single Sorted Array
using System
class GFG {
// Merge two sorted halves of Array
// into single sorted array
static void mergeTwoHalf(int[] A, int n)
{
int half_i = 0
// starting index of second half
int i
// Temp Array store sorted resultant array
int[] temp
= new int[n]
// First Find the point where array is divide
// into two half
for (i = 0 i < n - 1 i++)
{
if (A[i] > A[i + 1]) {
half_i = i + 1 break
}
}
// If Given array is all-ready sorted
if (half_i == 0)
return
// Merge two sorted arrays in single sorted
// array
i = 0 int j = half_i int k
= 0 while (i < half_i & &j < n)
{
if (A[i] < A[j])
temp[k++] = A[i++] else temp[k++]
= A[j++]
}
// Copy the remaining elements of A[i to half_!]
while (i < half_i)
temp[k++] = A[i++]
// Copy the remaining elements of A[half_!
// to n]
while (j < n) temp[k++]
= A[j++]
for (i = 0 i < n i++) A[i]
= temp[i]
}
// Driver code
static public void Main()
{
int[] A
= { 2,
3,
8,
-1,
7,
10 } int n
= A.Length mergeTwoHalf(A, n)
// Print sorted Array
for (int i = 0 i < n i++)
Console.Write(A[i] + " ")
}
}
// This code is contributed by vt_m .
JavaScript
<script>
// JavaScript program to Merge Two Sorted Halves Of
// Array Into Single Sorted Array
// Merge two sorted halves of Array into single
// sorted array
function mergeTwoHalf(A, n)
{
let half_i = 0; // starting index of second half
// Temp Array store sorted resultant array
let temp = new Array(n);
temp.fill(0);
// First Find the point where array is divide
// into two half
for (let i = 0; i < n - 1; i++) {
if (A[i] > A[i + 1]) {
half_i = i + 1;
break;
}
}
// If Given array is all-ready sorted
if (half_i == 0)
return;
// Merge two sorted arrays in single sorted array
let i = 0, j = half_i, k = 0;
while (i < half_i && j < n) {
if (A[i] < A[j])
temp[k++] = A[i++];
else
temp[k++] = A[j++];
}
// Copy the remaining elements of A[i to half_! ]
while (i < half_i)
temp[k++] = A[i++];
// Copy the remaining elements of A[ half_! to n ]
while (j < n)
temp[k++] = A[j++];
for (let i = 0; i < n; i++)
A[i] = temp[i];
}
let A = [ 2, 3, 8, -1, 7, 10 ];
let n = A.length;
mergeTwoHalf(A, n);
// Print sorted Array
for (let i = 0; i < n; i++)
document.write(A[i] + " ");
</script>
Time Complexity: O(n)
Space Complexity: O(n)
Reference: https://www.careercup.com/question?id=8412257
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 â Data Structure and Algorithm Tutorials 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 ImportantThe sorting algorithm is important in Com
3 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
14 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
9 min read