查找

package com.lkr.dataStructure;

import java.util.Scanner;

public class Search {

public static void main(String[] args){
int srcArrays[] = {3,5,11,17,21,23,28,30,32,50,64,78,81,95,101};
Scanner input = new Scanner(System.in);
System.out.println("请输入你要查找的数:");
int num = input.nextInt();
//int seqResult = sequentialSearch(srcArrays,21);
int seqResult = sequentialSearch(srcArrays,num);
if(seqResult == -1){
System.out.println("查找的数不再数组中");
}
else {
System.out.println("顺序查找结果:第" + (seqResult+1) + "个数,值为: " +srcArrays[seqResult] );
}
int binResult = binSearch(srcArrays,0, srcArrays.length-1,num);
if(binResult == -1){
System.out.println("你要查的数不存在");
}
else {

System.out.println("二分查找结果:第" + (binResult+1) + "个数,值为: " +srcArrays[binResult] );

}





}
//顺序查找算法:从表中的第一个(或最后一个)记录开始,逐个进行记录的关键字和给定值比较,若某个记录的关键字和给定值相等,
// 则查找成功,找到所查的记录;如果直到最后一个(或第一个)记录,其关键字和给定值比较都不等时,则表中没有多查的记录,查找不成功
public static int sequentialSearch(int[] a,int value){
/*int []b = new int[a.length+1];
b[0] = value;
for(int i=0;i<a.length;i++){
b[i+1] = a[i];
}
int j = a.length;
while (b[j] != value){
j--;
}

return j;*/
for(int i=0;i<a.length;i++){
if(a[i] == value){
return i;
}
}
return -1;

}

//二分查找递归实现
public static int binSearch(int[]a,int start,int end,int key){
int mid = (end - start)/2 +start;
if(start > end){
System.out.println("");
return -1;
}
if(key == a[mid]){
return mid;
}
else if(key > a[mid]){
return binSearch(a,mid+1,end,key);
}
else if(key < a[mid]){
return binSearch(a,start,mid-1,key);
}
return -1;
}


}
posted @ 2019-02-18 08:15  图图图图胡图图  阅读(227)  评论(0编辑  收藏  举报