码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2021-02-08 12:03:48      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:bool   ring   有序   str   length   false   组的复制   boolean   else   

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.length; 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 < arr.length; i++) {
arr2[i] = arr[arr.length - i-1];

}
// 遍历
for (int i = 0; i < arr2.length; i++) {
System.out.print(arr2[i] + "\t");
}
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";
String dest = "JJ";

boolean isFlag = true;
for (int i = 0; i < arr.length; 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 <= end) {
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] < select
head = middle + 1;
}
}
if (isFlag1) {
System.out.println("抱歉,没找到" + selectNumber);

}
}
}

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

标签:bool   ring   有序   str   length   false   组的复制   boolean   else   

原文地址:https://www.cnblogs.com/xjxlovehmx/p/14383082.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!