顺序查找
顺序查找:挨个查看
要求:对数组元素的顺序没要求
public static void arraySearch(int value) { int[] arr = {4, 5, 6, 1, 9}; //int value = 1; int index = -1; for (int i = 0; i < arr.length; i++) { if (arr[i] == value) { index = i; break; } } if (index == -1) { System.out.println(value + " 未找到..."); } else { System.out.println(value + " 找到了,索引是 " + index); } }
二分查找
举例:
实现步骤
参考
//二分查找 public static void binarySeach(int value) { //二分法查找:要求此数组必须是有序的。 int[] arr = new int[]{-99, -54, -2, 0, 2, 33, 43, 256, 999}; boolean ifFlag = true; int head = 0;//首索引位置 int end = arr.length - 1;//尾索引位置 while (head <= end) { int middle = (head + end) / 2; if (arr[middle] == value) { System.out.println("找到了,索引是 " + middle); ifFlag = false; break; } else if (arr[middle] > value) { end = middle - 1; } else { head = middle + 1; } } if (ifFlag) { System.out.println("没找到指定元素。是不是出错了..."); } }标签:index,arr,int,System,value,查找,数组,排序 From: https://www.cnblogs.com/wdh01/p/17212962.html