文章目錄
第七章 查找算法
本章源碼:https://github.com/name365/Java-Data-structure
線性查找分析和實現
有一個數列:{1,8, 10, 89, 1000, 1234},判斷數列中是否包含此名稱【順序查找】要求如果找到了,就提示找到,並給出下標值。
public class SeqSearch {
public static void main(String[] args) {
int arr[] = { 1, 9, 11, -1, 34, 89 }; //無序序列
// int arr[] = {1,8, 10, 89, 1000, 1234}; //有序序列
int index = seqSearch(arr, 34);
if(index == -1){
System.out.println("沒有找到");
}else{
System.out.println("找到了:" + index);
}
}
/**
*
* @Description 此處實現的線性查找是找到一個滿足條件的值,就返回
* @author subei
* @date 2020年5月30日下午6:30:16
* @param arr
* @param value
* @return
*/
public static int seqSearch(int[] arr,int value){
//線性查找是逐一比對,發現相同值,返回下標
for(int i = 0;i < arr.length;i++){
if(arr[i] == value){
return i;
}
}
return -1;
}
}
二分查找分析與實現
請對一個有序數組進行二分查找 {1,8, 10, 89, 1000, 1234} ,輸入一個數看看該數組是否存在此數,並且求出下標,如果沒有就提示"沒有這個數"。
二分查找的思路分析:
1. 首先確定該數組的中間的下標
mid = (left + right) / 2
2. 然後讓需要查找的數 findVal 和 arr[mid] 比較
2.1 findVal > arr[mid] , 說明你要查找的數在mid 的右邊, 因此需要遞歸的向右查找。
2.2 findVal < arr[mid], 說明你要查找的數在mid 的左邊, 因此需要遞歸的向左查找。
2.3 findVal == arr[mid] 說明找到,就返回。
//什麼時候我們需要結束遞歸.
1) 找到就結束遞歸。
2) 遞歸完整個數組,仍然沒有找到findVal ,也需要結束遞歸 當 left > right 就需要退出。
代碼實現:
//注意:使用二分查找的數組,必須是有序的。
public class BinarySearch {
public static void main(String[] args) {
int arr[] = {1,8, 10, 89, 1000, 1234};
int serch = binarySerch(arr, 0, arr.length - 1, 11);
System.out.println("serch = " + serch);
}
/**
*
* @Description 二分查找算法
* @author subei
* @date 2020年5月31日下午4:59:59
* @param arr 數組
* @param left 左邊的索引
* @param right 右邊的索引
* @param findVal 要查找的值
* @return 如果找到返回下標,反之,返回 -1
*/
public static int binarySerch(int arr[],int left,int right,int findVal){
//當left > right時,整個數組都沒有
if(left > right){
return -1;
}
int mid = (left + right) / 2;
int midVal = arr[mid];
if(findVal > midVal){ //向右遞歸
return binarySerch(arr, mid + 1, right, findVal);
}else if(findVal < midVal){ //向左遞歸
return binarySerch(arr, left, mid-1, findVal);
}else{
return mid;
}
}
}
算法的進一步優化:
{1,8, 10, 89, 1000, 1000,1234} 當一個有序數組中,有多個相同的數值時,如何將所有的數值都查找到,比如這裏的 1000.
import java.util.ArrayList;
import java.util.List;
//注意:使用二分查找的數組,必須是有序的。
public class BinarySearch2 {
public static void main(String[] args) {
int arr[] = {1,8, 10, 89, 1000,1000, 1234};
List<Integer> reget = binarySerch2(arr, 0, arr.length - 1, 89);
System.out.println("reget = " + reget);
}
//{1,8, 10, 89, 1000, 1000,1234}
//當一個有序數組中,有多個相同的數值時,如何將所有的數值都查找到,比如這裏的 1000.
//思路分析:
//1.在找到mid時,不馬上返回
//2.向mid索引值的左邊掃描,將所有滿足 1000的元素的下標,加入到集合ArrayList中
//3.向mid索引值的右邊掃描,將所有滿足 1000的元素的下標,加入到集合ArrayList中
//4.返回ArrayList集合
public static List<Integer> binarySerch2(int arr[],int left,int right,int findVal){
//當left > right時,整個數組都沒有
if(left > right){ //沒有這個判斷,會造成死遞歸!!!!
return new ArrayList<Integer>();
}
int mid = (left + right) / 2;
int midVal = arr[mid];
if(findVal > midVal){ //向右遞歸
return binarySerch2(arr, mid + 1, right, findVal);
}else if(findVal < midVal){ //向左遞歸
return binarySerch2(arr, left, mid-1, findVal);
}else{
List<Integer> reget = new ArrayList<Integer>();
//向mid索引值的左邊掃描,將所有滿足 1000的元素的下標,加入到集合ArrayList中
int temp = mid - 1;
while(true){
if(temp < 0 || arr[temp] != findVal){ //已經將最左邊都掃描完成
break;
}
//否則,就將temp放入集合
reget.add(temp);
temp -= 1; //向左移動temp
}
reget.add(mid); //放入中間值
//向mid索引值的右邊掃描,將所有滿足 1000的元素的下標,加入到集合ArrayList中
temp = mid + 1;
while(true){
if(temp > arr.length - 1 || arr[temp] != findVal){ //已經將最右邊都掃描完成
break;
}
//否則,就將temp放入集合
reget.add(temp);
temp += 1; //向右移動temp
}
return reget;
}
}
}
插值查找分析與實現
插值查找原理
插值查找算法類似於二分查找,不同的是插值查找每次從自適應mid處開始查找。
將折半查找中的求mid 索引的公式 , low 表示左邊索引left, high表示右邊索引right. key 就是前面我們講的findVal
- int mid = low + (high - low) * (key - arr[low]) / (arr[high] - arr[low]) ;/插值索引/
對應前面的代碼公式:
int mid = left + (right – left) * (findVal – arr[left]) / (arr[right] – arr[left])
舉例說明插值查找算法 1-100
具體思路:
數組 arr = [1, 2, 3, ......., 100]
假如我們需要查找的值 1
使用二分查找的話,我們需要多次遞歸,才能找到 1
使用插值查找算法:
int mid = left + (right – left) * (findVal – arr[left]) / (arr[right] – arr[left])
int mid = 0 + (99 - 0) * (1 - 1)/ (100 - 1) = 0 + 99 * 0 / 99 = 0
比如我們查找的值 100
int mid = 0 + (99 - 0) * (100 - 1) / (100 - 1) = 0 + 99 * 99 / 99 = 0 + 99 = 99
綜上,插值查找算法 ==》 套公式計算即可
應用案例
請對一個有序數組進行插值查找 {1,8, 10, 89, 1000, 1234} ,輸入一個數看看該數組是否存在此數,並且求出下標,如果沒有就提示"沒有這個數"。
public class InsertValueSearch {
public static void main(String[] args) {
int arr[] = {1,8, 10, 89, 1000, 1234};
int index = insertValue(arr, 0, arr.length - 1, 1234);
System.out.println("index = " + index);
int index2 = binarySerch(arr, 0, arr.length, 1234);
System.out.println("index2 = " + index2);
}
public static int binarySerch(int arr[],int left,int right,int findVal){
System.out.println("二分查找的調用:");
//當left > right時,整個數組都沒有
if(left > right){ //沒有這個判斷,會造成死遞歸!!!!
return -1;
}
int mid = (left + right) / 2;
int midVal = arr[mid];
if(findVal > midVal){ //向右遞歸
return binarySerch(arr, mid + 1, right, findVal);
}else if(findVal < midVal){ //向左遞歸
return binarySerch(arr, left, mid-1, findVal);
}else{
return mid;
}
}
/**
* 插值查找算法,也要求數組是有序的!!!
* @Description 插值查找算法
* @author subei
* @date 2020年5月31日下午9:43:59
* @param arr 數組
* @param left 左邊的索引
* @param right 右邊的索引
* @param findVal 查找的值
* @return 如果找到,就返回對應的下標,如果沒有找到,返回-1
*/
public static int insertValue(int arr[],int left,int right,int findVal){
System.out.println("查找的調用:");
//注意:findVal < arr[0] 和 findVal > arr[arr.length - 1] 必須需要
//否則將會得到的 mid可能越界
if (left > right || findVal < arr[0] || findVal > arr[arr.length - 1]) {
return -1;
}
//計算mid,自適應寫法
int mid = left + (right - left) * (findVal - arr[left]) / (arr[right] - arr[left]);
int midVal = arr[mid];
if(findVal > midVal){ //向右查找
return insertValue(arr, mid + 1, right, findVal);
}else if(findVal < midVal){ //向左查找
return insertValue(arr, left, mid - 1, findVal);
}else{ //找到了!!!
return mid;
}
}
}
- 插值查找注意事項:
- 對於數據量較大,關鍵字分佈比較均勻的查找表來說,採用插值查找,速度較快.
- 關鍵字分佈不均勻的情況下,該方法不一定比折半查找要好.
斐波那契查找分析與實現
-
斐波那契(黃金分割法)查找基本介紹
斐波那契(黃金分割法)原理
斐波那契查找原理與前兩種相似,僅僅改變了中間結點(mid)的位置,mid不再是中間或插值得到,而是位於黃金分割點附近,即mid=low+F(k-1)-1(F代表斐波那契數列),如下圖所示:
- 對F(k-1)-1的理解:
- 由斐波那契數列 F[k]=F[k-1]+F[k-2] 的性質,可以得到 (F[k]-1)=(F[k-1]-1)+(F[k-2]-1)+1 。該式說明:只要順序表的長度爲F[k]-1,則可以將該表分成長度爲F[k-1]-1和F[k-2]-1的兩段,即如上圖所示。從而中間位置爲mid=low+F(k-1)-1。
- 類似的,每一子段也可以用相同的方式分割。
- 但順序表長度n不一定剛好等於F[k]-1,所以需要將原來的順序表長度n增加至F[k]-1。這裏的k值只要能使得F[k]-1恰好大於或等於n即可,由以下代碼得到,順序表長度增加後,新增的位置(從n+1到F[k]-1位置),都賦爲n位置的值即可。
while(n > fib(k) - 1){
k++;
}
應用案例
請對一個有序數組進行斐波那契查找 {1,8, 10, 89, 1000, 1234} ,輸入一個數看看該數組是否存在此數,並且求出下標,如果沒有就提示"沒有這個數"。
import java.util.Arrays;
public class FibSearch {
public static int maxSize = 20;
public static void main(String[] args) {
int arr[] = { 1, 8, 10, 89, 1000, 1234 };
System.out.println("index = " + fibS(arr, 189));
}
// 因爲後面需要使用公式 mid=low+F(k-1)-1,因此需要先獲取到一個斐波那契數列
// 用非遞歸方法得到一個斐波那契數列
public static int[] fib() {
int f[] = new int[maxSize];
f[0] = 1;
f[1] = 1;
for (int i = 2; i < maxSize; i++) {
f[i] = f[i - 1] + f[i - 2];
}
return f;
}
/**
*
* @Description 使用非遞歸的方式編寫斐波那契算法
* @author subei
* @date 2020年5月31日下午10:20:37
* @param a
* 數組
* @param key
* 需要查找的關鍵碼(值)
* @return 返回對應的下標,如果沒有-1
*/
public static int fibS(int[] a, int key) {
int low = 0;
int hight = a.length - 1;
int k = 0; // 斐波那契數列的下標
int mid = 0; // 存放mid值
int f[] = fib(); // 獲取到斐波那契數列
// 獲取到斐波那契分割數值的下標
while (hight > f[k] - 1) {
k++;
}
// 因爲 f[k] 值 可能大於 a 的 長度,因此我們需要使用Arrays類,構造一個新的數組,並指向temp[]
// 不足的部分會使用0填充
int[] temp = Arrays.copyOf(a, f[k]);
// 實際上需求使用a數組最後的數填充 temp
// 舉例:
// temp = {1,8, 10, 89, 1000, 1234, 0, 0} =》 {1,8, 10, 89, 1000, 1234,
// 1234, 1234,}
for (int i = hight + 1; i < temp.length; i++) {
temp[i] = a[hight];
}
// 利用循環查找key
while (low <= hight) { // 滿足這個條件,即可以找到
mid = low + f[k - 1] - 1;
if (key < temp[mid]) { // 繼續向左邊查找
hight = mid - 1;
// 使用k--的原因
// 說明:
// 1.全部元素 = 前面的元素 + 後邊元素
// 2.f[k] = f[k-1] + f[k-2]
// 因爲 前面有 f[k-1]個元素,所以可以繼續拆分 f[k-1] = f[k-2] + f[k-3]
// 即 在 f[k-1] 的前面繼續查找 k--
// 即下次循環 mid = f[k-1-1]-1
k--;
} else if (key > temp[mid]) { // 繼續向右邊查找
low = mid + 1;
// 使用k -= 2 的原因
// 說明
// 1.全部元素 = 前面的元素 + 後邊元素
// 2.f[k] = f[k-1] + f[k-2]
// 3.因爲後面我們有f[k-2] 所以可以繼續拆分 f[k-1] = f[k-3] + f[k-4]
// 4.即在f[k-2] 的前面進行查找 k -= 2
// 5.即下次循環 mid = f[k - 1 - 2] - 1
k -= 2;
} else { // 找到了!!!
// 需要確定,返回的是哪個下標
if (mid <= hight) {
return mid;
} else {
return hight;
}
}
}
return -1;
}
}
本章思維導圖
第八章 哈希表
哈希表的介紹和內存佈局
先看一個實際需求,google公司的一個上機題:
有一個公司,當有新的員工來報道時,要求將該員工的信息加入(id,性別,年齡,住址…),當輸入該員工的id時,要求查找到該員工的 所有信息.
要求: 不使用數據庫,儘量節省內存,速度越快越好=>哈希表(散列)
散列表(Hash table,也叫哈希表),是根據關鍵碼值(Key value)而直接進行訪問的數據結構。也就是說,它通過把關鍵碼值映射到表中一個位置來訪問記錄,以加快查找的速度。這個映射函數叫做散列函數,存放記錄的數組叫做散列表。
所以什麼叫哈希表?
哈希表可以用來高效率解決元素不可重複這個問題,其本質就是:數組+鏈表+紅黑樹(後面會寫)。
哈希表實現
有一個公司,當有新的員工來報道時,要求將該員工的信息加入(id,性別,年齡,名字,住址…),當輸入該員工的id時,要求查找到該員工的所有信息。
要求:
1)不使用數據庫,,速度越快越好 => 哈希表(散列).
2)添加時,保證按照id從低到高插入
[課後思考:如果id不是從低到高插入,但要求各條鏈表仍是從低到高,怎麼解決?]
3)使用鏈表來實現哈希表,該鏈表不帶表頭[即:鏈表的第一個結點就存放僱員信息]
4)思路分析並畫出示意圖
思路圖解
- 使用哈希表來管理僱員信息
代碼實現
import java.util.Scanner;
public class HashTable {
public static void main(String[] args) {
//創建哈希表
HashTab hashTab = new HashTab(7);
//寫一個簡單的菜單
String key = "";
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("僱員管理系統:");
System.out.println("add : 添加僱員");
System.out.println("list: 顯示僱員");
System.out.println("find: 查找僱員");
System.out.println("del : 刪除僱員");
System.out.println("exit: 退出系統");
key = scanner.next();
switch (key) {
case "add":
System.out.print("輸入id:");
int id = scanner.nextInt();
System.out.print("輸入名字:");
String name = scanner.next();
//創建僱員
Emp emp = new Emp(id, name);
hashTab.add(emp);
break;
case "list":
hashTab.list();
break;
case "find":
System.out.print("請輸入需要查找的id:");
id = scanner.nextInt();
hashTab.findEmpId(id);
break;
case "del":
System.out.print("請輸入僱員的id:");
id = scanner.nextInt();
hashTab.delEmpId(id);
break;
case "exit":
scanner.close();
System.exit(0);
default:
break;
}
}
}
}
//創建HashTab
class HashTab{
private EmpLink[] empLinkArry;
private int size; //表示有多少條鏈表
//構造器
public HashTab(int size){
this.size = size;
//初始化empLinkArry
empLinkArry = new EmpLink[size];
//分別初始化每個鏈表,很重要!!!!
for(int i = 0; i < size; i++) {
empLinkArry[i] = new EmpLink();
}
}
//添加僱員
public void add(Emp emp){
//根據員工的ID,得到該員工應該到哪條鏈表
int empLinkNo = hashFun(emp.id);
//將emp添加到對應的鏈表中
empLinkArry[empLinkNo].add(emp);
}
//遍歷所有的鏈表,遍歷hashTab
public void list() {
for(int i = 0; i < size; i++) {
empLinkArry[i].list(i);
}
}
//編寫一個散列函數,使用一個簡單的取模法
public int hashFun(int id){
return id % size;
}
//根據輸入的id,查找僱員
public void findEmpId(int id){
//使用散列函數確定到哪條鏈表查找
int empLinkNO = hashFun(id);
Emp emp = empLinkArry[empLinkNO].findEmpId(id);
if(emp != null) {//找到
System.out.printf("在第%d條鏈表中找到,僱員 id = %d\n", (empLinkNO + 1), id);
}else{
System.out.println("在哈希表中,沒有找到該僱員~");
}
}
//根據僱員的Id從哈希表中刪除僱員
public void delEmpId(int id){
int index = hashFun(id);
empLinkArry[index].delEmp(id);
}
}
//表示一個僱員
class Emp{
public int id;
public String name;
public Emp next; // next默認爲 null
public Emp(int id, String name) {
super();
this.id = id;
this.name = name;
}
}
//創建一個EmpLink,表示鏈表
class EmpLink{
//頭指針,指向第一個Emp,因此這個鏈表的head是有效的,直接指向第一個Emp
private Emp head; //默認爲null
//添加僱員到鏈表
//說明
//1.假設,當添加僱員時,id是自增長,即id的分配總是從小到大
// 因此可以將該僱員直接加入到本鏈表的最後即可
public void add(Emp emp){
//如果是添加第一個僱員
if(head == null){
head = emp;
return;
}
//如果不是第一個,則使用一個輔助指針,幫助定位
Emp curEmp = head;
while(true){
if(curEmp.next == null){ //到達鏈表的最後
break;
}
curEmp = curEmp.next; //後移
}
//退出時直接將emp,加入鏈表
curEmp.next = emp;
}
//遍歷鏈表
public void list(int nums){
if(head == null){ //鏈表爲空
System.out.println("第" + (nums+1) + "鏈表爲空");
return;
}
System.out.println("第" + (nums+1) + "鏈表的信息:");
Emp curEmp = head; //輔助指針
while(true){
System.out.printf("=> id = %d name = %s\t",curEmp.id,curEmp.name);
if(curEmp.next == null){ //說明curEmp已經是最後的節點
break;
}
curEmp = curEmp.next; //後移
}
System.out.println();
}
//根據id查詢僱員
//如果查找到,就返回Emp,沒有找到,就返回null
public Emp findEmpId(int id){
//判斷鏈表是否爲空
if(head == null){
System.out.println("鏈表爲空.");
return null;
}
//輔助指針
Emp curEmp = head;
while(true){
if(curEmp.id == id){ //找到
break; //此時curEmp就指向要查找的僱員
}
//退出
if(curEmp.next == null){ //未找到該僱員
curEmp = null;
}
curEmp = curEmp.next; //後移
}
return curEmp;
}
//刪除僱員
public void delEmp(int id){
if(head == null){
System.out.println("沒有這個員工!!!");
return;
}
//如果刪除的是頭節點
if(head.id == id){
head = head.next;
return;
}
//如果刪除的不是頭節點
Emp temp = head;
while(temp.next != null){
if (temp.next.id == id) {
temp.next = temp.next.next;
System.out.println("Id爲" + id + "的員工已經被刪除~~");
return;
}
}
System.out.println("沒有這個員工!!!");
}
}
本章思維導圖
參考:http://baijiahao.baidu.com/s?id=1666172942887109917&wfr=spider&for=pc