一维数组的创建:
int[] array = {1, 2, 3};
int[] array2 = new int[]{4,5,6};
一维数组的遍历:
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
for (int i : array) {
System.out.println(i);
}
冒泡排序算法:
System.out.println("===========冒泡排序======================");
array = new int[]{3, 9, -1, 10, 20};
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
System.out.println(Arrays.toString(array));
选择排序算法:
System.out.println("=======选择排序==========================");
array = new int[]{3, 9, -1, 10, 20};
for (int i = 0; i < array.length; i++) {
int minNum = array[i];
for (int j = i + 1; j < array.length; j++) {
if (array[j] < minNum) {
array[i] = array[j];
array[j] = minNum;
}
}
}
System.out.println(Arrays.toString(array));
二分查找算法:
System.out.println("=======二分查找==========================");
array = new int[]{-1, 0, 3, 5, 9, 12};
int left = 0;
int right = array.length - 1;
int target = 9;
while (left <= right){
int middle = (left + right) / 2;
if(array[middle] == target){
System.out.println(target + "的位置的下标是"+ middle);
break;
}else if(array[middle] > target){
right--;
}else {
left++;
}
}
System.out.println("结束");
数组的拷贝扩容:
int[] array = {3, 9, -1, 10, 20};
int[] newArray = new int[5];
//数组的拷贝
System.arraycopy(array,0,newArray,0,array.length);
System.out.println(Arrays.toString(newArray));
newArray = Arrays.copyOf(array,array.length);
//数组的扩容(扩容到原来的两倍)
newArray = Arrays.copyOf(array,array.length * 2);
System.out.println(Arrays.toString(newArray));