31-数组转置案例分析

2020-11-08  本文已影响0人  c88bc9f9d088

    数组的反转操作指的是进行前后转置处理,即:首尾交换,例如,现在有一个数组,其内容如下:

    对于数组的前后交换有两种做法:

    做法一:定义一个新的数组而后按照逆序的方式保存(会产生无用的垃圾空间)

class ArrayUtil{
    public static void printArray(int temp[]){
        for(int x = 0; x < temp.length; x++){
            System.out.print(temp[x]+"、");
        }
    }
}
public  class ArrayDemo {
    public static void main(String args[]){
        int data[] = new int[]{1,2,3,4,5,6,7,8,9};
        int temp[] = new int[data.length];   //第二个数组
        int foot = temp.length - 1;  //第二个数组的脚标
        for(int x = 0; x < data.length; x++){
            temp[foot--] = data[x];
        }
        data = temp;
        ArrayUtil.printArray(data);
    }
}

    下面进行一下内存的分析处理,观察程序存在的问题。

做法二:在一个数组上进行转置

    现在如果要想实现这种转置最需要确定的就是数组转换的次数,次数的计算:“数组长度 ÷ 2”,实际上并不需要去考虑数组是奇数个数还是偶数个数。

class ArrayUtil{
    public static void printArray(int temp[]){
        for(int x = 0; x < temp.length; x++){
            System.out.print(temp[x]+"、");
        }
    }
}
public  class ArrayDemo {
    public static void main(String args[]){
        int data[] = new int[]{1,2,3,4,5,6,7,8,9};
        int center = data.length / 2 ; //确定转换的次数
        int head = 0; //操作脚标
        int tail = data.length - 1;  //操作脚标
        for(int x = 0; x < center; x++){ // 交换数据
            int temp = data[head]; 
            data[head] = data[tail];
            data[tail] = temp;
            head ++;
            tail --;
        }
        ArrayUtil.printArray(data);
    }
}

    两种实现如果要进行比较可以发现,第一种处理方式循环次数较多,并且还会产生垃圾,而第二种实现循环次数降低,但是存在有if判断增加了时间复杂度,可是可以减少无用对象的产生,以提升性能。

范例:将转换功能变为类定义

class ArrayUtil{
    public static void reverse(int data[]){
        int center = data.length / 2 ; //确定转换的次数
        int head = 0; //操作脚标
        int tail = data.length - 1;  //操作脚标
        for(int x = 0; x < center; x++){ // 交换数据
            int temp = data[head]; 
            data[head] = data[tail];
            data[tail] = temp;
            head ++;
            tail --;
        }
    }
    public static void printArray(int temp[]){
        for(int x = 0; x < temp.length; x++){
            System.out.print(temp[x]+"、");
        }
    }
}
public  class ArrayDemo {
    public static void main(String args[]){
        int data[] = new int[]{1,2,3,4,5,6,7,8,9};
        ArrayUtil.reverse(data); //转置处理
        ArrayUtil.printArray(data);
    }
}

    可以发现数组由于可以通过脚标进行元素的控制,所以相应的循环逻辑使用的会比较多。

上一篇 下一篇

猜你喜欢

热点阅读