Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- // Sort the columns by their sum, in ascending order.
- // The two-dimensional array (matrix).
- // 8 1 9 4
- // 3 2 1 2
- // 7 2 5 3
- const int ROWS = 3; // Length of each row and column.
- const int COLUMNS = 4; // Length of each row and column.
- int matrix[ROWS][COLUMNS] = { {8, 1, 9, 4}, {3, 2, 1, 2}, {7, 2, 5, 3} };
- // Get the sum of the numbers in one column.
- int get_column_sum(int arr[ROWS][COLUMNS], int column_index)
- {
- int sum = 0; // Start with a sum of zero.
- for (int i = 0; i < ROWS; ++i) // For each row,
- {
- // Add the number in the column indicated.
- sum += arr[i][column_index];
- }
- return sum;
- }
- // Swap two columns.
- void swap_columns(int arr[ROWS][COLUMNS], int columnA, int columnB)
- {
- int temp = 0; // This is temporary storage for the swap.
- for (int i = 0; i < ROWS; ++i) // For each row,
- {
- temp = arr[i][columnA]; // Store value in column1 in temp.
- // Move value in column2 to column1.
- arr[i][columnA] = arr[i][columnB];
- arr[i][columnB] = temp; // Move value in temp to column 2.
- }
- }
- // Display the matrix.
- void display_matrix(int arr[ROWS][COLUMNS])
- {
- for (int i = 0; i < ROWS; ++i) // For each row,
- {
- // For each item in the row,
- for (int j = 0; j < COLUMNS; ++j)
- {
- // Print the item.
- cout << arr[i][j] << " ";
- }
- cout << endl; // Go to the next line.
- }
- }
- int main()
- {
- // Display the unsorted matrix.
- display_matrix(matrix);
- // Store the lowest column in the unsorted part.
- int lowest_column = 0;
- // Mark the beginning of the current unsorted part.
- for (int i = 0; i <= COLUMNS - 2; ++i)
- {
- // Store the column index at the beginning of the
- // unsorted part as the lowest column.
- lowest_column = i;
- // For each of the columns that follow within the
- // unsorted part,
- for (int j = i + 1; j <= COLUMNS - 1; ++j)
- {
- // Compare the lowest column to it.
- // If the column sum is less,
- if (get_column_sum(matrix, j) // column that follows
- < get_column_sum(matrix, lowest_column)) // current lowest column
- {
- // Mark that column is less.
- lowest_column = j;
- }
- }
- // Swap the column with the first column in
- // the unsorted part, if the lowest column is different.
- if (i != lowest_column)
- {
- swap_columns(matrix, i, lowest_column);
- }
- }
- cout << endl; // Blank line.
- display_matrix(matrix); // Display the sorted matrix.
- // End the program.
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement