Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ Sorting algorithm that sorts every N elements of an array

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading