数组的复制/反转/查找(线性,二分法)

2021-03-04 01:26

阅读:517

public class ArrayListTest {
public static void main(String[] args) {
String[] arr = new String[]{"AA", "BB", "CC", "DD", "EE"};

// 数组的复制
String[] arr1 = new String[arr.length];
for (int i = 0; i arr1[i] = arr[i];
System.out.print(arr1[i] + "\t");
}
System.out.println();

// 数组的反转,两个方法
String arr2[] = new String[arr.length];
for (int i = 0; i arr2[i] = arr[arr.length - i-1];

}
// 遍历
for (int i = 0; i System.out.print(arr2[i] + "\t");
}
for (int i = 0,j = arr.length -1;i String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
for (int i = 0; i System.out.print(arr[i] + "\t");
}

System.out.println();
// 数组的查找,线性查找,
// String dest = "BB";
String dest = "JJ";

boolean isFlag = true;
for (int i = 0; i if (dest.equals(arr[i])) {
System.out.println("找到了,"+dest +"的位置为" + (i + 1));
isFlag = false;
break;
}
}
if (isFlag) {
System.out.println("很遗憾," +dest+ "没有找到");
}

// 二分法查找,比线性快.前提找的数组必须是有序的

int[] arrSelect = new int[]{-5, -1, 0,1, 5, 7, 11, 56};
int selectNumber = 0;
selectNumber = 100;
int head = 0;
int end = arrSelect.length - 1;
boolean isFlag1 = true;
while (head int middle = (head + end) / 2;

if (selectNumber == arrSelect[middle]) {
System.out.println("找到了,位置为:" + middle);
isFlag1 = false;
break;
} else if (arrSelect[middle] > selectNumber) {
end = middle - 1;
} else { // arrSelect[middle] head = middle + 1;
}
}
if (isFlag1) {
System.out.println("抱歉,没找到" + selectNumber);

}
}
}


评论


亲,登录后才可以留言!