Show the steps of Columnsort for the input array with 9 rows
Solution
Steps of Column-sort of an array:
1) Read the elements and store in 2-D array (arr[ ][ ])
2) Create a new 1-D array (newArr[ ])
3) Copy the 2-D array into 1-D array column wise
4) Apply any sorting algorithm to 1-D array
5) Copy or push back the sorted 1-D array into 2-D array column wise
6) Repeat the step 2 for each column of an 2-D array
7) Print the resulted 2-D array
Solution in JAVA:
package com.cg.cangg.columnsort;
import java.util.Arrays;
public class ColumnSort {
public static int arr[][] = new int[9][3];
   public static void readArray() {
        arr[0][0] = 23;
        arr[0][1] = 15;
        arr[0][2] = 9;
        arr[1][0] = 26;
        arr[1][1] = 11;
        arr[1][2] = 3;
        arr[2][0] = 2;
        arr[2][1] = 18;
        arr[2][2] = 7;
        arr[3][0] = 22;
        arr[3][1] = 5;
        arr[3][2] = 14;
       arr[4][0] = 17;
        arr[4][1] = 20;
        arr[4][2] = 25;
        arr[5][0] = 24;
        arr[5][1] = 10;
        arr[5][2] = 1;
        arr[6][0] = 8;
        arr[6][1] = 13;
        arr[6][2] = 21;
        arr[7][0] = 27;
        arr[7][1] = 12;
        arr[7][2] = 4;
       arr[8][0] = 19;
        arr[8][1] = 16;
        arr[8][2] = 6;
}
   public static void columnSort(int arr[][]) {
        for (int col = 0; col < arr[0].length; col++) {
            // Pull the column out.
            int[] thisCol = new int[arr.length];
            for (int i = 0; i < arr.length; i++) {
                thisCol[i] = arr[i][col];
            }
            // Sort it.
            Arrays.sort(thisCol); // predefined sort method in JAVA from util package
            // Push it back in.
            for (int i = 0; i < arr.length; i++) {
                arr[i][col] = thisCol[i];
            }
        }
    }
   public static void main(String[] args) {
        // TODO Auto-generated method stub
readArray(); // Reading the array elements
       System.out.println(\"Before sorting: \");
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(\" \" + arr[i][j]);
            }
            System.out.println();
        }
columnSort(arr); // calling columnSort method
       System.out.println(\"After sorting: \");
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(\" \" + arr[i][j]);
            }
            System.out.println();
        }
    }
 }


