public class ArrayTest3 {
public static void main(String[] args) {
String[] arr = new String[]{"SS","QQ","YY","XX","TT","KK","EE","GG"};
//数组的复制
String[] arr1 = new String[arr.length];
for(int i = 0;i < arr1.length;i++){
arr1[i] = arr[i];
}
//数组的反转
//方法一:
// for(int i = 0;i < arr.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");
}
System.out.println();
//查找(或搜索)
//线性查找
String dest = "BB"; //要查找的元素
dest = "CC";
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("很遗憾,没找到!");
}
//二分法查找:
//前提:所要查找的数组必须有序
int[] arr2 = new int[]{-98,-34,2,34,54,66,79,105,210,333};
int dest = 333;
int start = 0 ; //定义首索引
int end = arr2.length -1 ; // 定义末索引
boolean isBool = true;
while( start <= end ){
int middle = (start + end) /2;
if(dest == arr2[middle]){
System.out.println( "你找到了" + arr2[middle]);
isBool = false;
break;
} else if ( dest < arr2[middle]){
end = middle - 1;
}else{
start = middle + 1;
}
// System.out.println( "你找到了" + arr2[middle]);
}
if (isBool == true) {
System.out.println("未找到!很遗憾 ");
}
}
}
算法的考察:数组的复制、反转、查找(线性查找、二分法查找)
最新推荐文章于 2024-08-21 14:57:13 发布