java数组遍历与排序

示例代码:

java数组遍历与排序
package JavaPackageOne;

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] array = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
        Arrays.sort(array);
        // System.out.println(array);
        // System.out.println(Arrays.toString(array));
        printArray("length after sort: ", array);

        int index = Arrays.binarySearch(array, 2);
        System.out.println(index);
    }

    private static void printArray(String message, int array[]) {
        System.out.println(message + array.length);
        for (int i=0; i<array.length; i++) {
            if (i != 0) {
                System.out.print(", ");
            }
            System.out.print(array[i]);
        }
    }
}
View Code

1. 排序:

// 小到大,简洁的sort方法
Arrays.sort(array);
// 冒泡排序
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] ns = { 28, 12, 89, 73, 65, 18, 96, 50, 8, 36 };
        // 排序前:
        System.out.println(Arrays.toString(ns));
        for (int i = 0; i < ns.length - 1; i++) {
            for (int j = 0; j < ns.length - i - 1; j++) {
                if (ns[j] > ns[j+1]) {
                    // 交换ns[j]和ns[j+1]:
                    int tmp = ns[j];
                    ns[j] = ns[j+1];
                    ns[j+1] = tmp;
                }
            }
        }
        // 排序后:
        System.out.println(Arrays.toString(ns));
    }
}

 

找索引:

int index = Arrays.binarySearch(array, 2);

一维数组输出方法:

// 遍历输出
private static void printArray(String message, int array[]) {
System.out.println(message + array.length);
for (int i=0; i<array.length; i++) {
if (i != 0) {
System.out.print(", ");
}
System.out.print(array[i]);
}
}
// Arrays.toString(array)方法输出
System.out.println(Arrays.toString(array));

二维及多维数组输出:

// 两层嵌套的for循环
for (int[] arr : ns) {
    for (int n : arr) {
        System.out.print(n);
        System.out.print(', ');
    }
    System.out.println();
}
// 使用Java标准库的Arrays.deepToString()方法
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] ns = {
            { 1, 2, 3, 4 },
            { 5, 6, 7, 8 },
            { 9, 10, 11, 12 }
        };
        System.out.println(Arrays.deepToString(ns));
    }
}

 

2.遍历:

// for循环就可以遍历数组
public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        for (int i=0; i<ns.length; i++) {
            int n = ns[i];
            System.out.println(n);
        }
    }
}
// 使用for each循环,直接迭代数组的每个元素
public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        for (int n : ns) {
            System.out.println(n);
        }
    }
}

 

上一篇:Frida笔记


下一篇:【网络仿真】ns-3安装可视化工具PyViz&NetAnim