Assignment for C Programming - Recursion and Sorting

profilestudentineed
Task4.zip

Task4/output.txt

2 5 9 13 15 10 1 0 3 7 11 14 12 8 6 4 2 5 1 0 3 7 6 4 12 8 9 13 15 10 11 14 0 1 2 5 7 6 4 3 8 9 12 13 15 14 11 10 0 1 2 3 7 6 4 5 8 9 11 10 15 14 12 13 0 1 2 3 7 6 5 4 8 9 10 11 15 14 13 12

Task4/task4.cpp

#include <cstdio> #include <iostream> using namespace std; #define MAXROW 4 #define MAXCOL 4 void bidirection_bbsort(int a[], int n, bool ascending) { int i,j, temp; //This is the original bubble sort // Make SMALL change such that it handles descending sorting too for (i = n-1; i >= 1; i--) { for (j = 1; j <= i; j++) { if (a[j-1] > a[j]) { temp = a[j-1] ; a[j-1] = a[j] ; a[j] = temp ; } } } } void column_sort(int m[][MAXCOL], int col) { //Use the bidirection_bbsort() once it is implemented // No need to invent / write a new sorting logic } void print_matrix(int m[][MAXCOL], int nRow, int nCol) { int i, j; for (i = 0; i < nRow; i++){ for (j = 0; j < nCol; j++){ printf("%2d ", m[i][j]); //use printf for easier formatting //cout << setw(2) << m[i][j] << " "; //equivalent c++ output formatting } cout << endl; } cout << endl; } void phase_A(int mat[][MAXCOL], int nRow, int nCol) { int i; bool order = true; for (i = 0; i < nRow; i++, order = !order){ bidirection_bbsort(mat[i], nCol, order); } } void phase_B(int mat[][MAXCOL], int nRow, int nCol) { int i; for (i = 0; i < nCol; i++){ column_sort(mat, i); } } void magic_sort(int mat[][MAXCOL], int nRow, int nCol) { int i; for (i = 1; i < nRow; i *= 2){ phase_A(mat, nRow, nCol); print_matrix(mat, nRow, nCol); phase_B(mat, nRow, nCol); print_matrix(mat, nRow, nCol); } phase_A(mat, nRow, nCol); print_matrix(mat, nRow, nCol); } int main() { int arr[] = { 5, 12, 6, 7, 9, 6, 1}; int i; int mat[MAXROW][MAXCOL] = { {5, 2, 13, 9}, {10, 1, 15, 0}, {7, 3, 11, 14}, {12, 8, 4, 6} }; magic_sort(mat, 4, 4); return 0; }