0

I have a 2-dimensional(3x7) array. I would like to sort it per row. I have written a sample code.

 #define numRows 3
    #define numCols 7
int arr[numRows-1][numCols-1] = {{0,1,2,3,4,5,6}, {7,8,9,10,11,12,13},{14,15,16,17,18,19,20}};

    sort_row(arr);

    void sort_row(int *p)
    {
     for (int i = 0 ;i<numRows-1;i++)
     {
       sort(p[i][]);
     }
    }

    void sort(int *p)
    {
        for ( int c = 1 ; c <= numCols - 1 ; c++ )
        {
            for ( d = 0 ; d <= c - 1 ; d++ )
            {
                if ( array[c] < array[d] )
                {
                    swap = array[d];
                    array[d] = array[c];

                for ( int k = c ; k > d ; k-- )
                    array[k] = array[k-1];      

                array[k+1] = swap;
                }
            }
        }
    }

I am doing insertion sort for each row.

Qn: Am i passing the each row into sort properly? How can i improve it?

Looking for suggestion to improve that could improve or point out my mistakes in the code

3
  • Note d, n and swap are undeclared variables. Commented Feb 24, 2012 at 13:00
  • Did you test this code? Which is the initial value of n in sort()? Which are the values of numRows and numCols ? Why is arr dimensioned to numRows - 1 and numCols - 1? Commented Feb 24, 2012 at 13:05
  • i corrected the question now.... Commented Feb 24, 2012 at 13:14

3 Answers 3

1

Unless you really want to implement the sorting yourself, just use qsort().

Sign up to request clarification or add additional context in comments.

1 Comment

do i need to call any header file for that function?if so what?
0

No; p has been declared a pointer to an int in sort_row, so that p[i] would be an int, which you shouldn't be able to apply [] to, besides which, sort is expecting a pointer to an int.

Also, you have an executable statement (the call to sort_row) outside of any function.

Comments

0

after searching on @unwind ans, came up with this answer:

#include <stdlib.h>
#define numRows 3
#define numCols 7
int arr[numRows-1][numCols-1] = {{0,1,2,3,4,5,6}, {7,8,9,10,11,12,13},{14,15,16,17,18,19,20}};
int compare (const void * a, const void * b)
{
  return ( *(int*)a - *(int*)b );
}
void sort_row(int *p)
{
 for (int i = 0 ;i<numRows-1;i++)
 {
   qsort (p[i], 7, sizeof(int), compare);//sort(p[i]);
 }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.