How to quick sort a one dimentional array based on row and column in C or C++




Input 1D Array  
a[9]={33888,32567,3,32678,31967,2,32333,32456,0}

Described 1D array as row and column 


A         B          C
33888     32567      3
32678     31967      2
32333     32456      0


Need to sort this array based on column C

Output

32333
32456
0
32678
31967
2
33888
32567
3

 
Code:

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

int cmp( const void *a, const void *b )
{
    const int *p1 = ( const int * )a;
    const int *p2 = ( const int * )b;

    
    if(p2[2] < p1[2])
    {
        return 1;
    }
    else if (p1[2] < p2[2])
    {
        return -1;
    }

    return 0;

    //return ( p2[2] < p1[2] ) - ( p1[2] < p2[2] );
}

int main()
{

    int a[]  = {33888,32567,3,32678,31967,2,32333,32456,0},i;
    const size_t N = sizeof( a ) / sizeof( *a );
    const size_t M = N / 3; //Number of Row
    qsort( a, M, sizeof(int[3]), cmp ); //(int[3])={33888,32567,3}

    for (i = 0; i < N; i++ )
    {
        printf("%d\n",a[i]);
    }


    return 0;
}

Download Coding Interview Book and Get More Tutorials for Coding and Interview Solution: Click Here

Download System Design Interview Book and Get More Tutorials and Interview Solution: Click Here

Do you need more Guidance or Help? Then Book 1:1 Quick Call with Me: Click Here

Share on Google Plus

About Ashadullah Shawon

I am Ashadullah Shawon. I am a Software Engineer. I studied Computer Science and Engineering (CSE) at RUET. I Like To Share Knowledge. Learn More: Click Here
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment