1、线性查找
String[] arr = new String[]{"JJ","DD","MM","BB","GG","AA"};
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("很遗憾,没有找到!");
}
2、二分法查找
// 二分法查找:前提是所要查找的数组必须有序。
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("很遗憾,没有找到!");
}
3、冒泡排序
int[] arr = new int[]{43,32,76,-98,0,64,33,-21,32,99};
// 冒泡排序
for (int i = 0; i < arr.length - 1; i++) {
for(int j = 0;j < arr.length -1 - i ;j++){
if(arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + "\t");
}
网友评论