算法(二):查找

一 、 线性查找(顺序查找)

public class LSearch {
public static int[] Data = { 12, 76, 29, 22, 15, 62, 29, 58, 35, 67,
58, 33, 28, 89, 90, 28, 64, 48, 20, 77 }; // 输入数据数组

public static int Counter = 1; // 查找次数计数变量

public static void main(String args[]) {

int KeyValue = 22;
// 调用线性查找
if (Linear_Search((int) KeyValue)) {
// 输出查找次数
System.out.println("");
System.out.println("Search Time = " + (int) Counter);
} else {
// 输出没有找到数据
System.out.println("");
System.out.println("No Found!!");
}
}

// ---------------------------------------------------
// 顺序查找
// ---------------------------------------------------
public static boolean Linear_Search(int Key) {
int i; // 数据索引计数变量

for (i = 0; i < 20; i++) {
// 输出数据
System.out.print("[" + (int) Data[i] + "]");
// 查找到数据时
if ((int) Key == (int) Data[i])
return true; // 传回true
Counter++; // 计数器递增
}
return false; // 传回false
}
}

 

二 、二分查找折半查找

public class BSearch {
public static int Max = 20;
public static int[] Data = { 12, 16, 19, 22, 25, 32, 39, 48, 55, 57,
58, 63, 68, 69, 70, 78, 84, 88, 90, 97 }; // 数据数组
public static int Counter = 1; // 计数器

public static void main(String args[]) {
int KeyValue = 22;
// 调用折半查找
if (BinarySearch((int) KeyValue)) {
// 输出查找次数
System.out.println("");
System.out.println("Search Time = " + (int) Counter);
} else {
// 输出没有找到数据
System.out.println("");
System.out.println("No Found!!");
}
}

// ---------------------------------------------------
// 折半查找法
// ---------------------------------------------------
public static boolean BinarySearch(int KeyValue) {
int Left; // 左边界变量
int Right; // 右边界变量
int Middle; // 中位数变量

Left = 0;
Right = Max - 1;

while (Left <= Right) {
Middle = (Left + Right) / 2;
if (KeyValue < Data[Middle]) // 欲查找值较小
Right = Middle - 1; // 查找前半段
// 欲查找值较大
else if (KeyValue > Data[Middle])
Left = Middle + 1; // 查找后半段
// 查找到数据
else if (KeyValue == Data[Middle]) {
System.out
.println("Data[" + Middle + "] = " + Data[Middle]);
return true;
}
Counter++;
}
return false;
}
}

 

转载于:https://www.cnblogs.com/wytiger/p/5341271.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值