I am looking for an algorithm that sorts every N element of an array.
For example lets says The array is 7 8 6 4 5 1 4 3 5 and N is 3.
I want the sorted array to be 6 7 8 1 4 5 3 4 5
Please note that the array size is a multiple of N.
I wrote the below algorithm for N==3 but not sure how to handle for higher value of N
for ( ll i=0;i<N;i+=3)
{
if (A1[i]> A1[i+1])
{
swap(A1[i+1],A1[i]);
}
if(A1[i+1] > A1[i+2])
{
swap(A1[i+2],A1[i+1]);
}
}
>Solution :
Obligatory solution using C++20 ranges:
#include <algorithm>
#include <iostream>
#include <ranges>
int main()
{
int arr[] = {7,8,6,4,5,1,4,3,5};
int n = 3;
for (auto &&segment : arr | std::views::chunk(n))
std::ranges::sort(segment);
for (int x : arr)
std::cout << x << ' ';
std::cout << '\n';
}
But since you’re probably asked to implement this manually: Make a sorting function (using whatever algorithm you want) that just sorts an entire array. It will probably accept a pointer and a length as parameters (or two pointers). You can then apply it to individual subarrays in a loop.