This blog is under construction

Saturday 27 July 2013

C program to sort two dimensional array in ascending order

Write a C program to sort a matrix in ascending order.


  #include <stdio.h>
  #define ROW 10
  #define COL 10

  int main() {
        int matrix[ROW][COL];
        int i, j, k, l, n, temp;

        /* get the order of the matrix from the user */
        printf("Enter the order of the matrix:");
        scanf("%d", &n);

        /* get the matrix entries from the user */
        printf("Enter your entries for the input matrix:\n");
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        scanf("%d", &matrix[i][j]);
                }
        }

        /* sort the contents of the two dimensional array */
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        temp = matrix[i][j];
                        l = j + 1;
                        for (k = i; k < n; k++) {
                                while (l < n) {
                                        /* swapping the data */
                                        if (temp > matrix[k][l]) {
                                                temp = matrix[k][l];
                                                matrix[k][l] = matrix[i][j];
                                                matrix[i][j] = temp;
                                        }
                                        l++;
                                }
                                l = 0;
                        }
                }
        }

        /* print the result */
        printf("\n");
        printf("Resultant Matrix:\n");
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        printf("%d ", matrix[i][j]);
                }
                printf("\n");
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the order of the matrix:3
  Enter your entries for the input matrix:
  10 90 80
  70 20 60
  50 40 30

  Resultant Matrix:
  10 20 30 
  40 50 60 
  70 80 90 


No comments:

Post a Comment