
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort Elements of Array 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
#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
Advertisements