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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA 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 RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem