#002线性查找和二分查找 #4

Merged
sawyergore merged 1 commits from feature_20220721 into master 2022-07-22 22:36:39 +08:00
4 changed files with 77 additions and 5 deletions
Showing only changes of commit 2b13c1eae4 - Show all commits

View File

@ -0,0 +1,49 @@
package sort;
/**
* 二分查找,对于目标数组必须有序
* @author Sawyer
* @date 2022/7/22
*/
public class TestBinarySearch {
public static void main(String[] args) {
//目标数组
int [] arr = new int []{1,2,3,4,5,6,7,8,9};
//目标元素
int target = 8;
//目标元素下标
int index = -1;
//记录开始位置
int begin = 0;
//记录结束位置
int end = arr.length-1;
//记录中间位置
int mid = (begin+end)/2;
int i =0;
//循环查找
while (i<arr.length){
//判断中间的元素是不是要查找的元素
if(arr[mid]==target){
index = mid;
break;
//不是要查找的元素
}else {
//判断中间元素是否比目标元素大
if(arr[mid]>target){
//把结束位置调整到中间位置前一个位置
end = mid-1;
//中间这个元素比目标元素小
}else {
//把开始位置调整到中间位置的后一个位置
begin = mid+1;
}
//取出新的中间位置
mid=(begin+end)/2;
i++;
}
}
System.out.println("index:"+index);
}
}

View File

@ -0,0 +1,28 @@
package sort;
/**
* 线性查找
* @author Sawyer
* @date 2022/7/22
*/
public class TestSearch {
public static void main(String[] args) {
/*
目标数组
*/
int[] arr = new int[]{1,2,3,4,5,6,7};
//目标元素
int target=3;
//目标元素所在下标
int index=-1;
for (int j : arr) {
if (j == target) {
index = target;
break;
}
}
//打印目标元素下标
System.out.println("index"+index);
}
}

View File

@ -1,7 +1,6 @@
package com.example.h2db;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.annotation.MapperScans;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

View File

@ -1,9 +1,5 @@
package com.example.h2db.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**