数组的基本使用
package com.ShuJu;
public class TestArray {
public static void main(String[] args) {
int[] arr1 = new int[3];
int length1 = arr1.length;
System.out.println("arr1's length: " + length1);
int element0 =arr1[0];
System.out.println("element0:"+element0);
arr1[0] = 99;
System.out.println("element0:"+arr1[0]);
arr1[1] = 98;
arr1[2] = 97;
for(int i = 0 ; i < length1; i++){
System.out.println("arr1 element"+ i +":" + arr1[i]);
}
int[] arr2 = new int[] {99,98,97,96,95};
System.out.println("arr2 length:" + arr2.length);
}
}
数组的删除
package com.ShuJu;
import java.util.Arrays;
import java.util.Scanner;
public class TestArray1 {
public static void main(String[] args) {
int[] arr = new int[] {9,8,7,6,5,4};
System.out.println(Arrays.toString(arr));
System.out.println("请输入您要删除第几个元素:");
Scanner input = new Scanner(System.in);
int dst = input.nextInt() -1 ;
int[] newArr = new int[arr.length-1];
for(int i = 0 ; i < newArr.length ; i++){
if(i < dst){
newArr[i] = arr[i];
}else{
newArr[i] = arr[i + 1];
}
}
arr = newArr;
System.out.println(Arrays.toString(arr));
}
}
在指定位置添加元素
package com.ShuJu;
import java.util.Arrays;
import java.util.Scanner;
public class TestArray2 {
public static void main(String[] args) {
int[] arr = new int[]{1,2,3,5,6,8,};
Scanner input = new Scanner(System.in);
System.out.println("请输入插入的位置和元素:");
int index = input.nextInt() - 1;
int element = input.nextInt();
int[] newArr = new int[arr.length + 1 ];
for(int i = 0 ; i < arr.length ;i++){
if(i < index){
newArr[i] = arr[i];
}else{
newArr[i + 1] = arr[i];
}
}
newArr[index] = element;
arr = newArr;
System.out.println(Arrays.toString(arr));
}
}
遍历查找元素
一一对比,相同则返回。
二分查找算法
前提:该数组是有序的,无序数组无法使用。
package com.ShuJu;
public class TestArray3 {
public static void main(String[] args) {
int[] arr = new int[]{1,2,3,4,5,6,7,8,9};
int target = 9;
int begin = 0 ;
int end = arr.length -1;
int mid = (begin + end ) / 2;
int index = -1 ;
while (true){
if(arr[mid] == target){
index = mid;
break;
}else{
if(arr[mid] > target){
end = mid -1;
}else{
begin = mid + 1 ;
}
mid = (begin + end )/2;
}
}
System.out.println("index:"+ index);
}
}
|