Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,872 questions

51,796 answers

573 users

How to flatten a 2D array into a sorted one-dimensional array in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

#define ROWS 3
#define COLS 4
#define SIZE ROWS * COLS

int compare(const void *a, const void *b) {
    return (*(int*)a - *(int*)b);
}

void Flatten2DArrayIntoSorted1DArray(int array2d[][COLS], int rows, int cols, int arr[]) {
    int index = 0;

    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            if (array2d[i][j] != 0) {
                arr[index++] = array2d[i][j];
            }
        }
    }

    qsort(arr, index, sizeof(int), compare);
}


int main() {
    int array2d[][COLS] = {
        { 4,  5, 9, 2},
        {30, 20, 3, 1},
        {10, 19, 6, 8},
    };
    
    int arr[SIZE];
    
    Flatten2DArrayIntoSorted1DArray(array2d, ROWS, COLS, arr);

    for (int i = 0; i < SIZE; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}


/*
run:

1 2 3 4 5 6 8 9 10 19 20 30 

*/

 



answered Aug 15, 2024 by avibootz
...