复制
package project01;
public class ArrayExer2 {
public static void main(String[] args) {
int[] array1,array2;
array1 = new int[]{2,3,5,7,11,13,17,19}; //其实只有一个数组,
//显示array1的内容
for (int i =0; i< array1.length;i++){
System.out.print(array1[i] + "\t");
}
//赋值array2变量等于array1
array2 = array1; //地址一样,给了array2
//修改array2中的偶索引元素,使其等于索引值(如array[0]=0,array[2]=2)
for(int i = 0;i< array2.length;i++){
if (i%2==0){
array2[i]=i;
}
}
System.out.println();
//打印出array1
for (int i=0;i<array1.length;i++){
System.out.print(array1[i] + "\t");
}
}
}
array2=array1不能称作数组的复制,array2和array1地址值相同
反转
public class ArrayExer2 {
public static void main(String[] args) {
String[] arr = new String[]{"JJ","DD","MM","BB","GG","AA"};
//数组的复制(区别于数组变量的赋值,arr1=arr)
String[] arr1 = new String[arr.length];
for (int i=0; i< arr.length;i++){
arr1[i] = arr[i];
}
//数组的反转
//反转操作
for (int i =0;i< arr1.length/2;i++){
String temp =arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i -1] = temp;
}
//遍历
for (int i=0;i< arr.length;i++){
System.out.print(arr[i] + "\t");
}
}
}
public class ArrayExer2 {
public static void main(String[] args) {
String[] arr = new String[]{"JJ","DD","MM","BB","GG","AA"};
//数组的复制(区别于数组变量的赋值,arr1=arr)
String[] arr1 = new String[arr.length];
for (int i=0; i< arr.length;i++){
arr1[i] = arr[i];
}
//数组的反转
//反转操作
//方法一
/*
for (int i =0;i< arr1.length/2;i++){
String temp =arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i -1] = temp;
}
*/
//方法二
for (int i=0,j=arr.length-1;i<j;i++,j--){
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
//遍历
for (int i=0;i< arr.length;i++){
System.out.print(arr[i] + "\t");
}
}
}
查找
线性查找
public class ArrayExer2 {
public static void main(String[] args) {
String[] arr = new String[]{"JJ","DD","MM","BB","GG","AA"};
//数组的复制(区别于数组变量的赋值,arr1=arr)
String[] arr1 = new String[arr.length];
for (int i=0; i< arr.length;i++){
arr1[i] = arr[i];
}
//数组的反转
//查找操作
//线性查找
String dest = "BB";
boolean isFlag = true;
for (int i = 0;i< arr.length;i++){
if(dest.equals(arr[i])){
System.out.println("找到了指定的元素,位置为:" + i);
isFlag = false;
break;
}
}
if(isFlag){
System.out.println("很遗憾,没有找到!");
}
//遍历
for (int i=0;i< arr.length;i++){
System.out.print(arr[i] + "\t");
}
}
}
二分法查找
package project01;
public class ArrayExer2 {
public static void main(String[] args) {
String[] arr = new String[]{"JJ","DD","MM","BB","GG","AA"};
//数组的复制(区别于数组变量的赋值,arr1=arr)
String[] arr1 = new String[arr.length];
for (int i=0; i< arr.length;i++){
arr1[i] = arr[i];
}
//数组的反转
//查找操作
//二分法查找
//前提:所要查找的数组必须有序
int[] arr2 = new int[]{-96,-35,2,25,96,245,524,1231};
int dest1 = -35;
int head =0;//初始的首索引
int end = arr2.length -1;//初始的末索引
while (head <= end){
int middle = (head +end)/2;
if (dest1 == arr2[middle]){
System.out.println("找到了指定的元素,位置为: " + middle);
break;
}else if (arr2[middle]>dest1){
end = middle-1;
}else{//arr2[middle]>dest1
head = middle+1;
}
}
//遍历
}
}
}