Java two-dimensional array row and column interchange

Source: Internet
Author: User

Code Requirements:

A two-dimensional array of peer rows and columns is interchanged

Analysis process
    • The main diagonal is kept constant
    • The row and column interchange is the Angle label interchange: [0][1] [1][0]
    • Loop count: Outer loop row, inner Loop column for each row

Code implementation
public class ArrayReverse {    public static void main(String[] args) {        int arry[][] = new int[][] {{1,2,3},{4,5,6},{7,8,9}};        reverse(arry);        printArray(arry);    }    /**     * 二维数组转置     * @param arry     */    public static void reverse(int arry[][]) {        int count = 0;//用于统计总共循环次数        for(int i=0; i< arry.length-1; i++) {            //列循环从:i+1开始,提高循环效率            for(int j=i+1; j< arry[i].length; j++) {                int temp = arry[i][j];                arry[i][j] = arry[j][i];                arry[j][i] = temp;                count++;            }        }        System.out.println(count);    }        public static void printArray(int array[][]){        for(int i=0;i<array.length; i++) {            for(int j = 0; j< array[i].length; j++) {                System.out.print(array[i][j]+"、");            }            System.out.println();        }    }}
Summarize

The starting point of the inner Loop (column loop) loop = Outer Loop +1, which saves cycle times and improves efficiency than the j=0 cycle.

If there is a better algorithm, but also look for friends to help improve the message!

Java two-dimensional array row and column interchange

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.