top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Can someone please write a C program for the given below problem ?

+3 votes
354 views

Given a 2d array, u need to sort the 2 diagonals independently.
And the elements in diagonal should remain in diagonal only.

INPUT =>
24 2 3 4 7

6 13 8 5 10

11 12 9 14 15

16 21 18 25 20

17 22 23 24 1

OUTPUT =>
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

posted Oct 12, 2013 by Neeraj Mishra

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+5 votes
int main ()
{
    for(i=0;i<dem;i++)
    for(j=0;j<dem;j++)
    {
        printf("\nEnter the element a[%d][%d] = ",i,j);
        scanf("%d",&a[i][j]);
        if(i+j == dem-1)
            dig2[i]=a[i][j];           /* store the dignole element in array */
        if(i==j)
            dig1[i]=a[i][j];          /* store the dignole element in array */
    }
   dig_sort(dig1,dig2,dem);
}

 /*  This function check array is sorted  */
 /*  If array is sort return 1 otherwise return 0 */
int checksort(int *a,int dem)
{
    int i;  /* for loop */

    for(i=0;i<dem-1;i++)
        if(a[i]>a[i+1])
            return 0;
    return 1;
}

/*  This function sort the dignole of matrix   */   
void dig_sort(int *dig1,  int *dig2,  int dem)
{
    if(!checksort(dig1,dem))  /* check sort the 1st array */
        sort(dig1,dem);   /* position of middle element has change */

    if(dem%2!=0)    /* if array's digonal has odd no of element */
        dig2[dem/2]=dig1[dem/2];   /* change middle element */

    if(!checksort(dig2,dem))
        sort(dig2,dem);

    if(dem%2!=0)    /* if digonal of array has odd no of element change middle element */
        dig1[dem/2]=dig2[dem/2];

    if(!(checksort(dig1,dem) && checksort(dig2,dem)))  /* check both array is sorted */
        dig_sort(dig1,dig2,dem);        /* if both are bot sorted then recursive call */

} 

/*  This function to sort the ARRAY  */   
void sort(int *a, int size)
{
    /* Any sort can be used here Merge , Quick and Heap sort  */
    /* Whichever you like most or as per situation. */
}
answer Oct 12, 2013 by Vikas Upadhyay
...