Qsort in two dimensional array

Hello, I want to ask you all to help me finish this code I don't know what is the problem. I know what the qsort needs to do.It worked int 1D array ,but in 2d array it doesn't working.
The question is: what I need to do sort every row in 2d array with qsort ? Also how I supposed to do ?
Anyway here is my code:

#include <iostream>
#include <fstream>
#include <stdlib.h>

using namespace std;

int double_cmp(const void*,const void* );
int main()
{
ifstream fin; fin.open("bemenet.txt");
if(!fin.is_open()){cout << "Error!!! "; return 0;}
ofstream fout; fout.open("kimenet.txt");
if(!fout.is_open()){cout << "Error!!! "; return 0;}
int n,i,m,j;
double **a;
fin >> n >> m;
a = (double**)malloc(n*sizeof(double*)); if(a == 0){cout << "Error:"; return 0;};
for(i = 0; i < n; ++i){
a[i] = (double*)malloc(m*sizeof(double)); if(a == 0){cout << "Error:"; return 0;};
for(j = 0; j < m; ++j){
fin >> a[i][j];
}
}
qsort(a, n, sizeof(double),double_cmp);
for(i = 0; i < n; ++i){
for(j = 0;j < m; ++j){
fout << a[i][j] << " " ;
}
fout << endl;
}


for(i = 0; i < n; ++i)
free(a[i]);
free(a);
fin.close();
fout.close();

return 0;
}

int double_cmp ( const void *p1, const void *p2 )
{
double *q1 = (double *)p1;
double *q2 = (double *)p2;
if ( *q1 > *q2 ) { return -1; }
else if ( *q1 < *q2 ) { return 1; }
else { return 0; }
}
Just took a skim over your code, but assuming qsort works on 1d like you said, try the following:
It seems your array is n by m and thus quicksort should be looped over all n rows while sorting the m length rows.
1
2
for (int i = 0; i < n; ++i)
    qsort(a[i], m, sizeof(double),double_cmp);
Last edited on
Same as above, polymorphic, stylised:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <cstdlib>

template < typename T > int compare( const void* pa, const void* pb )
{
    const T& a = *static_cast< const T* >(pa) ;
    const T& b = *static_cast< const T* >(pb) ;
    return (a>b) - (b>a) ;
}

template < typename T > void qsort( T* pa, std::size_t sz ) { if(pa) std::qsort( pa, sz, sizeof(T), compare<T> ) ; }

int main()
{
    const std::size_t NROWS = 3 ;
    const std::size_t NCOLS = 5 ;
    int array[NROWS][NCOLS] = { { 1, 5, 9, 2, 7 }, { 8, 1, 7, 4, 0 }, { 1, 3, 5, 4, 2 } };

    for( auto& row : array ) qsort( row, NCOLS ) ;
    // for( std::size_t i = 0 ; i < NROWS ; ++i ) qsort( array[i], NCOLS ) ;

    for( auto& row : array )
    {
        for( int v : row ) std::cout << v << ' ' ;
        std::cout << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/846e30e832fb3560
Thank you all,It is working now :)
Topic archived. No new replies allowed.