Sort elements of the array that occurs in between multiples of K in C++


Suppose we have an array A, and another integer K. We have to sort the elements that are in between any two multiples of K. Suppose A is like [2, 13, 3, 1, 21, 7, 8, 13, 12], and K = 2. The output will be [2, 1, 3, 7, 13, 21, 8, 13, 12]. Here multiple of 2 are 2, 8 and 12, the elements in between 2 and 8 are 13, 3, 1, 21, 7, they will be sorted as 1, 3, 7, 13, 21, the elements between 8 and 12 is only 13, so that is already sorted.

We have to traverse the array, and keep track of the multiple of the value K. Then starting from second multiple of K, sort every element between the current and previous multiple of K.

Example

 Live Demo

#include <iostream>
#include <algorithm>
using namespace std;
void display(int arr[], int n) {
   for (int i = 0; i < n; i++)
   cout << arr[i] << " ";
}
void sortBetweenMultipleOfK(int arr[], int n, int k) {
   int prev_index = -1;
   for (int i = 0; i < n; i++) {
      if (arr[i] % k == 0) {
         if (prev_index != -1) //check whether that is not the first multiple of k
         sort(arr + prev_index + 1, arr + i);
         prev_index = i;
      }
   }
}
int main() {
   int arr[] = {2, 13, 3, 1, 21, 7, 8, 13, 12};
   int n = sizeof(arr) / sizeof(arr[0]);
   int k = 2;
   cout << "Before Sort: "; display(arr, n);
   sortBetweenMultipleOfK(arr, n, k);
   cout << "\nAfter Sort : "; display(arr, n);
}

Output

Before Sort: 2 13 3 1 21 7 8 13 12
After Sort : 2 1 3 7 13 21 8 13 12

Updated on: 21-Oct-2019

67 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements