天天看點

大資料:大資料之數組

大資料:大資料之數組

1.5.1 數組的定義與元素通路

數組是一個容器, 是一個用來存儲指定資料類型的容器

注意事項:

  1. 數組是一個定長的容器, 一旦執行個體化完成, 長度不能修改

    名詞解釋:

  2. 數組長度: 指的就是這個容器的容量, 表示這個數組中能存儲多少個資料
  3. 元素: 指的就是數組中存儲的資料
  4. 下标: 某一個元素在數組中的一個位置索引
  5. 周遊數組: 依次擷取到數組中的每一個元素

    數組的元素通路

通過下标來通路的, 數組中元素的下标是從0開始的

數組中元素的下标: [0, 數組.length - 1]

注意:

在通路數組中元素的時候, 注意下标的範圍, 不要越界!!!

周遊數組:

  1. 使用循環周遊下标的方式
    int[] array = {1, 2, 3};
    for (int index = 0; index < array.length; index++) {
        System.out.println(array[index]);
    }           
  2. 使用增強for循環
    int[] array = {1, 2, 3};
    for (int ele : array) {
        System.out.println(ele);
    }           
    1.5.2 數組的記憶體分析

1.5.3 數組的常見操作

1.5.4 數組排序

選擇排序

固定一個下标, 然後用這個下标對應的元素依次和後面每一個下标的元素進行比較

int[] array = {1, 3, 5, 7, 9, 0, 8, 6, 4, 2};
for (int index = 0; index < array.length - 1; index++) {
    for (int compare = index + 1; compare < array.length; compare++) {
        if (array[index] < array[compare]) {
            int temp = array[index];
            array[index] = array[compare];
            array[compare] = temp;
        }
    }
}           

冒泡排序

依次比較數組中兩個相鄰的元素

int[] array = {1, 3, 5, 7, 9, 0, 8, 6, 4, 2};
for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array.length - 1 - i; j++) {
        if (array[j] < array[j + 1]) {
            int temp = array[j];
            array[j] = array[j + 1];
            array[j + 1] = temp;
        }
    }
}           

1.5.5 數組元素查找

從一個數組中查詢指定的元素出現的下标

  1. 順序查找
  2. 二分查找

    1.5.6 二維數組

繼續閱讀