树的引子, 顺序查找和二分查找

Posted hi3254014978

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了树的引子, 顺序查找和二分查找相关的知识,希望对你有一定的参考价值。

顺序查找

1 Position SequentialSearch(List Tbl, ElementType K)
2 {
3     Position i;
4     Tbl->Data[0] = K;
5     for (i = Tbl->Last; Tbl->Data[i] != K; i--);
6     return i;
7 }

二分查找

 1 Position BinarySearch(List Tbl, ElementType K)
 2 {
 3     Position Left, Right, Mid;
 4     Left = 1;
 5     Right = Tbl->Last;
 6     
 7     while (Left <= Right)
 8     {
 9         Mid = (Left + Right) / 2;
10         if (Tbl->Data[Mid] < K) 
11             Left = Mid + 1;
12         else if (Tbl->Data[Mid] > K) 
13             Right = Mid - 1;
14         else
15             return Mid;
16     }
17     return NotFound;
18 }

测试这两个查找的剩余代码

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 #define MAXSIZE 15
 5 typedef int ElementType;
 6 typedef int Position;
 7 #define NotFound 0        //找不到则返回0
 8 
 9 struct Array{
10     ElementType Data[MAXSIZE];
11     int Last;
12 };
13 typedef struct Array* List;
14 
15 List CreateArray()
16 {
17     List Tbl = (List)malloc(sizeof(struct Array));        //已经为Data数组分配好了空间
18     printf("%d
", sizeof(struct Array));
19     //Tbl->Data = (ElementType*)malloc(sizeof(ElementType) * MAXSIZE);
20     Tbl->Last = 0;
21     return Tbl;
22 }
23 
24 void InsertA(List Tbl, ElementType X)
25 {
26     Tbl->Data[++Tbl->Last] = X;
27 }
 1 int main()
 2 {
 3     List Tbl = CreateArray();
 4     int result;
 5     for (int i = 0; i <10; i++)
 6         InsertA(Tbl, i + 15);
 7     for (int i = 0; i < Tbl->Last; i++)
 8         printf("%d ", Tbl->Data[i]);
 9 
10     //result = SequentialSearch(Tbl, 19);
11     result = BinarySearch(Tbl, 19);
12     if (result)
13         printf("
Find %d at index %d
", 19, result);
14     else
15         printf("
Not found
");
16 
17     for (int i = 0; i < Tbl->Last; i++)
18         printf("%d ", Tbl->Data[i]);
19     return 0;
20 }

 

以上是关于树的引子, 顺序查找和二分查找的主要内容,如果未能解决你的问题,请参考以下文章

顺序查找和二分查找代码

搜索插入位置(数组二分查找)买蛋(算法) 二叉树的前序遍历(栈树)

二分查找和二分查找树的区别

(王道408考研数据结构)第七章查找-第二节2:二分查找及其判定树

leetcode查找算法(顺序查找,二分法,斐波那契查找,插值查找,分块查找)

二分查找和顺序查找