好程序員大數據教程分享實用的大數據之數組
1.5.1 數組的定義與元素訪問
數組是一個容器, 是一個用來存儲指定數據類型的容器
注意事項:
- 數組是一個定長的容器, 一旦實例化完成, 長度不能修改
名詞解釋:
- 數組長度: 指的就是這個容器的容量, 表示這個數組中能存儲多少個數據
- 元素: 指的就是數組中存儲的數據
- 下標: 某一個元素在數組中的一個位置索引
- 遍歷數組: 依次獲取到數組中的每一個元素
數組的元素訪問
通過下標來訪問的, 數組中元素的下標是從0開始的
數組中元素的下標: [0, 數組.length - 1]
注意:
在訪問數組中元素的時候, 注意下標的範圍, 不要越界!!!
遍歷數組:
-
使用循環遍歷下標的方式
int[] array = {1, 2, 3}; for (int index = 0; index < array.length; index++) { System.out.println(array[index]); }
-
使用增強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 數組元素查找
從一個數組中查詢指定的元素出現的下標
- 順序查找
- 二分查找