Open In App

Sort a K-Increasing-Decreasing Array

Last Updated : 15 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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


Output

57 131 190 221 294 339 418 442 458 493

Time Complexity: O(n*logk), where n is the length of array.
 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads