C program: Sorting Matrix Elements

Source: Internet
Author: User

Requirement:

Write a program to sort the elements of m x n matrix A in descending order. Suppose M and N do not exceed 10. Write the functions to calculate the largest element value and the smallest element value in one-dimensional array respectively. The main function initializes a two-dimensional array a [10] [10], call the defined two functions to output the maximum values of each row and column.

Code:

// MatrixSort.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include iostream.h>void bubble_sort(int a[],int n){    int temp=0;    for( int i=0;in;i++ )    for(int j=n-1;j>i;j--)    {        if(a[i]a[j])        {            temp=a[i];            a[i]=a[j];            a[j]=temp;        }    }}void bubble_sort2(int** a,int n){    int temp=0;    for( int i=0;i
 
   )    for(int j=n-1;j>i;j--)    {        if(**(a+i)**(a+j))        {            temp=**(a+i);            **(a+i)=**(a+j);            **(a+j)=temp;        }    }}void formatMatrix(int* matrix, int linesize , int columnsize){for(int j=0 ; jcolumnsize ; j++){int** col = new int*[linesize] ;for(int i=0 ; ilinesize ; i++ )*(col+i) = matrix+i*columnsize+j;bubble_sort2(col ,linesize ) ;delete[] col ;}}void showMaxAndMin(int* matrix, int linesize , int columnsize){int* max = new int[columnsize] ;int* min = new int[columnsize] ;for (int i=0; icolumnsize; i++){max[i] = *(matrix+i) ;min[i] = *(matrix+(linesize-1)*columnsize+i) ;}coutendl
  ;coutMin value: " ;for (int j=0; jcolumnsize; j++){coutmin[j]coutendl ;coutMax value: " ;for (int k=0; kcolumnsize; k++){coutmax[k]coutendlendl ;delete[] max ;delete[] min ;}int main(int argc, char* argv[]){int a[5][5] = {{1,3,8,2,4},{5,2,8,9,3},{4,1,6,0,7},{3,0,1,2,5},{8,3,0,8,4},} ;// Calculate linesize and columnsize of matrixint columnsize = sizeof(a[0])/sizeof(int) ;int linesize = sizeof(a)/sizeof(int)/columnsize ;coutColumn Size="Line Size=" " ;}coutendl ;}//Print min and max values for each columnshowMaxAndMin(*a, linesize, columnsize) ;return 0;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.