1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| public class ArrayTest2 { public static void main(String[] args) { String[] arr = new String[]{"JJ","DD","MM","BB","GG","AA"}; 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;i++){ System.out.print(arr[i] + "\t"); } System.out.println(); 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("很遗憾,没有找到的啦!"); } int[] arr2 = new int[]{-98,-34,2,34,54,66,79,105,210,333}; int dest1 = -34; int head = 0; int end = arr2.length - 1; boolean isFlag1 = true; while(head <= end){ int middle = (head + end)/2; if(dest1 == arr2[middle]){ System.out.println("找到了指定的元素,位置为:" + middle); isFlag1 = false; break; }else if(arr2[middle] > dest1){ end = middle - 1; }else{ head = middle + 1; }
} if(isFlag1){ System.out.println("很遗憾,没有找到的啦!"); } } }
|