Sort a K-Increasing-Decreasing Array
Last Updated :
12 Jul, 2025
Given a K-increasing-decreasing array arr[], the task is to sort the given array. An array is said to be K-increasing-decreasing if elements repeatedly increase upto a certain index after which they decrease, then again increase, a total of K times. The diagram below shows a 4-increasing-decreasing array.

Example:
Input: arr[] = {57, 131, 493, 294, 221, 339, 418, 458, 442, 190}
Output: 57 131 190 221 294 339 418 442 458 493
Input: arr[] = {1, 2, 3, 4, 3, 2, 1}
Output: 1 1 2 2 3 3 4
Approach: The brute-force approach is to sort the array without taking advantage of the k-increasing-decreasing property. The time complexity of this approach is O(n logn) where n is the length of the array.
If k is significantly smaller than n, a better approach can be found with less time complexity. For example, if k=2, the input array consists of two subarrays, one increasing, the other decreasing. Reversing the second subarray yields two sorted arrays and the result is then merged which can be done in O(n) time. Generalizing, we could first reverse the order of each of the decreasing subarrays. For example, in the above figure, the array could be decomposed into four sorted arrays as {57, 131, 493}, {221, 294}, {339, 418, 458} and {190, 442}. Now the min-heap technique can be used to merge these sorted arrays.
Below is the implementation of the above approach:
CPP
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// A pair of pairs, first element is going to
// store value, second element index of array
// and third element index in the array
typedef pair<int, pair<int, int> > ppi;
// This function takes an array of arrays as an
// argument and all arrays are assumed to be
// sorted
// It merges them together and returns the
// final sorted output
vector<int> mergeKArrays(vector<vector<int> > arr)
{
vector<int> output;
// Create a min heap with k heap nodes
// Every heap node has first element of an array
priority_queue<ppi, vector<ppi>, greater<ppi> > pq;
for (int i = 0; i < arr.size(); i++)
pq.push({ arr[i][0], { i, 0 } });
// Now one by one get the minimum element
// from min heap and replace it with next
// element of its array
while (pq.empty() == false) {
ppi curr = pq.top();
pq.pop();
// i ==> Array Number
// j ==> Index in the array number
int i = curr.second.first;
int j = curr.second.second;
output.push_back(curr.first);
// The next element belongs to same array as
// current
if (j + 1 < arr[i].size())
pq.push({ arr[i][j + 1], { i, j + 1 } });
}
return output;
}
// Function to sort the alternating
// increasing-decreasing array
vector<int> SortKIncDec(const vector<int>& A)
{
// Decompose the array into a
// set of sorted arrays
vector<vector<int> > sorted_subarrays;
typedef enum { INCREASING,
DECREASING } SubarrayType;
SubarrayType subarray_type = INCREASING;
int start_idx = 0;
for (int i = 0; i <= A.size(); i++) {
// If the current subarrays ends here
if (i == A.size()
|| (i>0 && A[i - 1] < A[i]
&& subarray_type == DECREASING)
|| (i>0 && A[i - 1] >= A[i]
&& subarray_type == INCREASING)) {
// If the subarray is increasing
// then add from the start
if (subarray_type == INCREASING) {
sorted_subarrays.emplace_back(A.cbegin() + start_idx,
A.cbegin() + i);
}
// If the subarray is decreasing
// then add from the end
else {
sorted_subarrays.emplace_back(A.crbegin()
+ A.size() - i,
A.crbegin()
+ A.size()
- start_idx);
}
start_idx = i;
subarray_type = (subarray_type == INCREASING
? DECREASING
: INCREASING);
}
}
// Merge the k sorted arrays`
return mergeKArrays(sorted_subarrays);
}
// Driver code
int main()
{
vector<int> arr = { 57, 131, 493, 294, 221,
339, 418, 458, 442, 190 };
// Get the sorted array
vector<int> ans = SortKIncDec(arr);
// Print the sorted array
for (int i = 0; i < ans.size(); i++)
cout << ans[i] << " ";
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
public class Main {
static class Pair implements Comparable<Pair> {
int first, second, third;
// A pair of pairs, first element is going to
// store value, second element index of array
// and third element index in the array
public Pair(int f, int s, int t) {
first = f;
second = s;
third = t;
}
public int compareTo(Pair p) {
return Integer.compare(first, p.first);
}
}
// This function takes an array of arrays as an
// argument and all arrays are assumed to be
// sorted
// It merges them together and returns the
// final sorted output
static List<Integer> mergeKArrays(List<List<Integer>> arr) {
List<Integer> output = new ArrayList<>();
// Create a min heap with k heap nodes
// Every heap node has first element of an array
PriorityQueue<Pair> pq = new PriorityQueue<>();
for (int i = 0; i < arr.size(); i++) {
pq.add(new Pair(arr.get(i).get(0), i, 0));
}
// Now one by one get the minimum element
// from min heap and replace it with next
// element of its array
while (!pq.isEmpty()) {
Pair curr = pq.poll();
// i ==> Array Number
// j ==> Index in the array number
int i = curr.second;
int j = curr.third;
output.add(curr.first);
// The next element belongs to same array as
// current
if (j + 1 < arr.get(i).size()) {
pq.add(new Pair(arr.get(i).get(j + 1), i, j + 1));
}
}
return output;
}
enum SubarrayType {
INCREASING, DECREASING
}
// Function to sort the alternating
// increasing-decreasing array
public static List<Integer> SortKIncDec(final List<Integer> A) {
// Decompose the array into a
// set of sorted arrays
List<List<Integer>> sorted_subarrays = new ArrayList<>();
SubarrayType subarray_type = SubarrayType.INCREASING;
int start_idx = 0;
for (int i = 0; i <= A.size(); i++) {
// If the current subarrays ends here
if (i == A.size()
|| (i > 0 && A.get(i - 1) < A.get(i)
&& subarray_type == SubarrayType.DECREASING)
|| (i > 0 && A.get(i - 1) >= A.get(i)
&& subarray_type == SubarrayType.INCREASING)) {
// If the subarray is increasing
// then add from the start
if (subarray_type == SubarrayType.INCREASING) {
sorted_subarrays.add(A.subList(start_idx, i));
// If the subarray is decreasing
// then add from the end
} else {
List<Integer> subList = new ArrayList<>(A.subList(start_idx, i));
Collections.reverse(subList);
sorted_subarrays.add(subList);
}
start_idx = i;
subarray_type = (subarray_type == SubarrayType.INCREASING
? SubarrayType.DECREASING : SubarrayType.INCREASING);
}
}
// Merge the k sorted arrays`
return mergeKArrays(sorted_subarrays);
}
// Driver code
public static void main(String[] args) {
List<Integer> arr = Arrays.asList(57, 131, 493, 294, 221, 339, 418, 458, 442, 190);
List<Integer> ans = SortKIncDec(arr);
for (int i = 0; i < ans.size(); i++) {
System.out.print(ans.get(i) + " ");
}
}
}
// This code is contributed by Shiv1o43g
Python3
import heapq
# This function takes an array of arrays as an
# argument and all arrays are assumed to be
# sorted
# It merges them together and returns the
# final sorted output
def mergeKArrays(arr):
output = []
# Create a min heap with k heap nodes
# Every heap node has first element of an array
pq = []
for i in range(len(arr)):
heapq.heappush(pq, (arr[i][0], i, 0))
# Now one by one get the minimum element
# from min heap and replace it with next
# element of its array
while pq:
curr = heapq.heappop(pq)
# i ==> Array Number
# j ==> Index in the array number
i, j = curr[1], curr[2]
output.append(curr[0])
# The next element belongs to same array as
# current
if j + 1 < len(arr[i]):
heapq.heappush(pq, (arr[i][j + 1], i, j + 1))
return output
# Function to sort the alternating
# increasing-decreasing array
def SortKIncDec(A):
# Decompose the array into a
# set of sorted arrays
sorted_subarrays = []
INCREASING, DECREASING = range(2)
subarray_type = INCREASING
start_idx = 0
for i in range(len(A) + 1):
# If the current subarrays ends here
if (i == len(A)
or (i>0 and A[i - 1] < A[i]
and subarray_type == DECREASING)
or (i>0 and A[i - 1] >= A[i]
and subarray_type == INCREASING)):
# If the subarray is increasing
# then add from the start
if subarray_type == INCREASING:
sorted_subarrays.append(A[start_idx:i])
# If the subarray is decreasing
# then add from the end
else:
sorted_subarrays.append(A[i-1:start_idx-1:-1])
start_idx = i
subarray_type = DECREASING if subarray_type == INCREASING else INCREASING
# Merge the k sorted arrays
return mergeKArrays(sorted_subarrays)
# Driver code
arr = [57, 131, 493, 294, 221, 339, 418, 458, 442, 190]
# Get the sorted array
ans = SortKIncDec(arr)
# Print the sorted array
for i in range(len(ans)):
print(ans[i], end=' ')
# This code is contributed by Prince Kumar
C#
using System;
using System.Collections.Generic;
class Program
{
// A pair of pairs, first element is going to
// store value, second element index of array
// and third element index in the array
class Triplet : IComparable<Triplet>
{
public int Value { get; set; }
public Tuple<int, int> ArrayIndex { get; set; }
public int CompareTo(Triplet other)
{
return this.Value.CompareTo(other.Value);
}
}
// Enum for subarray types
enum SubarrayType
{
INCREASING,
DECREASING
}
// Merges K sorted arrays into a final sorted output
static List<int> MergeKArrays(List<List<int>> arr)
{
var output = new List<int>();
var pq = new SortedSet<Triplet>();
for (int i = 0; i < arr.Count; i++)
pq.Add(new Triplet { Value = arr[i][0], ArrayIndex = Tuple.Create(i, 0) });
while (pq.Count > 0)
{
Triplet curr = pq.Min;
pq.Remove(curr);
int i = curr.ArrayIndex.Item1;
int j = curr.ArrayIndex.Item2;
output.Add(curr.Value);
if (j + 1 < arr[i].Count)
pq.Add(new Triplet { Value = arr[i][j + 1], ArrayIndex = Tuple.Create(i, j + 1) });
}
return output;
}
// Sorts the alternating increasing-decreasing array
static List<int> SortKIncDec(List<int> A)
{
var sortedSubarrays = new List<List<int>>();
SubarrayType subarrayType = SubarrayType.INCREASING;
int startIdx = 0;
for (int i = 0; i <= A.Count; i++)
{
if (i == A.Count ||
(i > 0 && A[i - 1] < A[i] && subarrayType == SubarrayType.DECREASING) ||
(i > 0 && A[i - 1] >= A[i] && subarrayType == SubarrayType.INCREASING))
{
if (subarrayType == SubarrayType.INCREASING)
{
sortedSubarrays.Add(A.GetRange(startIdx, i - startIdx));
}
else
{
var sub = A.GetRange(startIdx, i - startIdx);
sub.Reverse();
sortedSubarrays.Add(sub);
}
startIdx = i;
subarrayType = (subarrayType == SubarrayType.INCREASING ? SubarrayType.DECREASING : SubarrayType.INCREASING);
}
}
return MergeKArrays(sortedSubarrays);
}
static void Main(string[] args)
{
List<int> arr = new List<int> { 57, 131, 493, 294, 221, 339, 418, 458, 442, 190 };
List<int> ans = SortKIncDec(arr);
foreach (var value in ans)
{
Console.Write(value + " ");
}
}
}
JavaScript
// Javascript implementation of the approach
// A pair of pairs, first element is going to
// store value, second element index of array
// and third element index in the array
class Pair {
constructor(f, s, t) {
this.first = f;
this.second = s;
this.third = t;
}
compareTo(p) {
return this.first - p.first;
}
}
class PriorityQueue {
constructor(comparator = (a, b) => a - b) {
this.heap = [];
this.comparator = comparator;
}
size() {
return this.heap.length;
}
peek() {
return this.heap[0];
}
push(...values) {
values.forEach(value => {
this.heap.push(value);
this.bubbleUp(this.heap.length - 1);
});
}
pop() {
const poppedValue = this.peek();
const bottom = this.size() - 1;
if (bottom > 0) {
this.swap(0, bottom);
}
this.heap.pop();
this.bubbleDown(0);
return poppedValue;
}
bubbleUp(index) {
while (index > 0) {
const parentIndex = Math.floor((index + 1) / 2) - 1;
if (this.comparator(this.heap[parentIndex], this.heap[index]) <= 0) {
break;
}
this.swap(parentIndex, index);
index = parentIndex;
}
}
bubbleDown(index) {
while (true) {
const leftChildIndex = 2 * index + 1;
const rightChildIndex = 2 * index + 2;
let smallestChildIndex = index;
if (
leftChildIndex < this.size() &&
this.comparator(this.heap[leftChildIndex], this.heap[smallestChildIndex]) <= 0
) {
smallestChildIndex = leftChildIndex;
}
if (
rightChildIndex < this.size() &&
this.comparator(this.heap[rightChildIndex], this.heap[smallestChildIndex]) <= 0
) {
smallestChildIndex = rightChildIndex;
}
if (smallestChildIndex === index) {
break;
}
this.swap(smallestChildIndex, index);
index = smallestChildIndex;
}
}
swap(index1, index2) {
[this.heap[index1], this.heap[index2]] = [this.heap[index2], this.heap[index1]];
}
}
// This function takes an array of arrays as an
// argument and all arrays are assumed to be
// sorted
// It merges them together and returns the
// final sorted output
function mergeKArrays(arr) {
const output = [];
// Create a min heap with k heap nodes
// Every heap node has first element of an array
const pq = new PriorityQueue((a, b) => a.compareTo(b));
for (let i = 0; i < arr.length; i++) {
pq.push(new Pair(arr[i][0], i, 0));
}
// Now one by one get the minimum element
// from min heap and replace it with next
// element of its array
while (pq.size() > 0) {
const curr = pq.pop();
// i ==> Array Number
// j ==> Index in the array number
const i = curr.second;
const j = curr.third;
output.push(curr.first);
// The next element belongs to same array as
// current
if (j + 1 < arr[i].length) {
pq.push(new Pair(arr[i][j + 1], i, j + 1));
}
}
return output;
}
const SubarrayType = {
INCREASING: 0,
DECREASING: 1,
};
// Function to sort the alternating
// increasing-decreasing array
function SortKIncDec(A) {
// Decompose the array into a
// set of sorted arrays
const sorted_subarrays = [];
let subarray_type = SubarrayType.INCREASING;
let start_idx = 0;
for (let i = 0; i <= A.length; i++) {
// If the current subarrays ends here
if (i === A.length ||(i > 0 && A[i - 1] < A[i] &&
subarray_type === SubarrayType.DECREASING) ||
(i > 0 &&
A[i - 1] >= A[i] &&
subarray_type === SubarrayType.INCREASING)
) {
// If the subarray is increasing
// then add from the start
if (subarray_type === SubarrayType.INCREASING) {
sorted_subarrays.push(A.slice(start_idx, i));
}
// If the subarray is decreasing
// then add from the end
else {
const subList = A.slice(start_idx, i).reverse();
sorted_subarrays.push(subList);
}
start_idx = i;
subarray_type =
subarray_type === SubarrayType.INCREASING
? SubarrayType.DECREASING
: SubarrayType.INCREASING;
}
}
// Merge the k sorted arrays`
return mergeKArrays(sorted_subarrays);
}
// Driver code
const arr = [57, 131, 493, 294, 221, 339, 418, 458, 442, 190];
const ans = SortKIncDec(arr);
for (let i = 0; i < ans.length; i++) {
console.log(ans[i] + " ");
}
// This code is contributed by Shivhack999
Output57 131 190 221 294 339 418 442 458 493
Time Complexity: O(n*logk), where n is the length of array.
Similar Reads
Increasing Decreasing Update Queries (Akku and Arrays) Akku has solved many problems, she is a genius. One day her friend gave her an Array of sizes n and asked her to perform some queries of the following type: Each query consists of three integers 1 A B: Update the Array at index A by value B2 A B: if the subarray from index A to B (both inclusive) is
15+ min read
Operations to Sort an Array in non-decreasing order Given an array arr[] of integers of size n, the task is to check if we can sort the given array in non-decreasing order(i, e.arr[i] ⤠arr[i+1]) by using two types of operation by performing any numbers of time: You can choose any index from 1 to n-1(1-based indexing) and increase arr[i] and arr[i+1]
7 min read
Sort an Array by decreasing and increasing elements with adjacent swaps Given an array arr[] of size N. The task is to make an array in increasing order where you are allowed (any number of times) to swap adjacent elements and decrease the value with a smaller index by 1 and increase the value of a greater index by 1. Output "Yes" if it is possible to arrange the array
7 min read
Print array elements in alternatively increasing and decreasing order Given an array of N elements. The task is to print the array elements in such a way that first two elements are in increasing order, next 3 in decreasing order, next 4 in increasing order and so on. Examples: Input : arr = {2, 6, 2, 4, 0, 1, 4, 8, 2, 0, 0, 5,2,2} Output : 0 0 8 6 5 0 1 2 2 4 4 2 2 2
12 min read
Split the array elements into strictly increasing and decreasing sequence Given an array of N elements. The task is to split the elements into two arrays say a1[] and a2[] such that one contains strictly increasing elements and the other contains strictly decreasing elements and a1.size() + a2.size() = a.size(). If it is not possible to do so, print -1 or else print both
7 min read
Minimum increment/decrement to make array non-Increasing Given an array a, your task is to convert it into a non-increasing form such that we can either increment or decrement the array value by 1 in the minimum changes possible. Examples : Input : a[] = {3, 1, 2, 1}Output : 1Explanation : We can convert the array into 3 1 1 1 by changing 3rd element of a
11 min read