Search code examples
carrayscomplexity-theoryarray-algorithms

Double dimension array sorting in O(n) time


I was asked a question in interview for sorting a double dimension array in O(n) time.How is it possible to do it in O(n).Can someone shed some light on it.. Thank you.

Input:

3 5 7 1
4 9 2 0
9 3 6 2   

Output

0 1 2 2 
3 3 4 5  
6 7 9 9

Solution

  • You can sort as a plain array.
    E.g.

    #include <stdio.h>
    #include <stdlib.h>
    
    
    int cmp(const void *a, const void *b){
        return *(int*)a - *(int*)b;
    }
    
    #define ROW_SIZE 3
    #define COL_SIZE 4
    
    int main(void){
        int M[ROW_SIZE][COL_SIZE]={{3,5,7,1},{4,9,2,0},{9,3,6,2}};
        int c,r,*p;
    
        for(p=&M[0][0],r=0;r<ROW_SIZE;++r){
            for(c=0;c<COL_SIZE;++c){
                printf("%d ",*p++);
            }
            printf("\n");
        }
        printf("\n");
        qsort(&M[0][0], ROW_SIZE*COL_SIZE, sizeof(int), cmp);
        for(p=&M[0][0],r=0;r<ROW_SIZE;++r){
            for(c=0;c<COL_SIZE;++c){
                printf("%d ",*p++);
            }
            printf("\n");
        }
    
        return 0;
    }