qsort() 2d dynamic array
Apr 10, 2015 at 7:36am UTC
ascending sort. rows wont be sorted internally.
comparison of row n and row m:
if row[n][0] < row[m][0] row[n] precedes row[m]
if row[n][0] > row[m][0] row[m] precedes row[n]
if row[n][0] == row[m][0] compare row[n][1] and row[m][1] so on ...
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
//
#include <iostream>
#include <cstdlib> // qsort
using namespace std;
const int row = 4;
const int col = 3;
int qCompare (const void *a1,const void *b1){ // ascending
const int *a = (const int *)a1;
const int *b = (const int *)b1;
for (int i=0; i<col; i++){
if (a[i]<b[i]) return -1;
else if (a[i]>b[i]) return 1;
}
return 0;
}
int main () {
int **arr;
arr = new int *[row];
for (int i=0; i<row; i++) {
arr[i] = new int [col];
}
arr[0][0]=5; arr[0][1]=1; arr[0][2]=1;
arr[1][0]=8; arr[1][1]=4; arr[1][2]=2;
arr[2][0]=7; arr[2][1]=2; arr[2][2]=3;
arr[3][0]=8; arr[3][1]=2; arr[3][2]=4;
cout << "initial array \n" ;
for (int i=0; i<row; i++) {
for (int j=0; j<col; j++) {
cout << arr[i][j] << " " ;
}
cout << "\n" ;
}
cout << "\n" ;
qsort(arr, row, col*sizeof (int ), qCompare); ///
cout << "after qsort \n" ;
for (int i=0; i<row; i++) {
for (int j=0; j<col; j++) {
cout << arr[i][j] << " " ;
}
cout << "\n" ;
}
cout << "\n" ;
return 0;
}
i think arr has been inaccessible after qsort calling.
how to fix it?
EDIT:
after sorting the correct arr should contain this:
Last edited on Apr 10, 2015 at 7:49am UTC
Apr 10, 2015 at 10:39am UTC
solved.
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
//
#include <iostream>
#include <cstdlib> // qsort
using namespace std;
const int row = 4;
const int col = 3;
int qCompare (const void *a1,const void *b1){ // ascending
const int *a = *(const int **)a1;
const int *b = *(const int **)b1;
for (int i=0; i<col; i++){
if (a[i] != b[i]) return a[i]-b[i];
}
return 0;
}
int main () {
int **arr;
arr = new int *[row];
for (int i=0; i<row; i++) {
arr[i] = new int [col];
}
arr[0][0]=5; arr[0][1]=1; arr[0][2]=1;
arr[1][0]=8; arr[1][1]=4; arr[1][2]=2;
arr[2][0]=7; arr[2][1]=3; arr[2][2]=3;
arr[3][0]=8; arr[3][1]=2; arr[3][2]=4;
cout << "initial array \n" ;
for (int i=0; i<row; i++) {
for (int j=0; j<col; j++) {
cout << arr[i][j] << " " ;
}
cout << "\n" ;
}
cout << "\n" ;
qsort(arr, row, sizeof arr[0], qCompare); ///
cout << "after qsort \n" ;
for (int i=0; i<row; i++) {
for (int j=0; j<col; j++) {
cout << arr[i][j] << " " ;
}
cout << "\n" ;
}
cout << "\n" ;
return 0;
}
Topic archived. No new replies allowed.