数据--第47课 - 查找的概念

第47课 - 查找的概念

1. 查找的定义

(1)      查找表是由同一类型的数据元素构成的集合。

(2)      查找是根据给定的某个值,在查找表中确定一个其关键字等于给定值的数据元素。

注意:

l  从逻辑意义上来说,查找表中的数据元素之间没有本质的关系。

l  查找表可以不是线性表,树结束和图结构的任意一种。

 

2. 查找的概念

(1)查找的操作

静态查找:

查询某个特定的数据元素是否在查找表中。

检索某个特定的数据元素的各种属性。

动态查找:

在查找中插入一个数据元素。

从查找表中删去某个数据元素。

(2)查找表中的关键字

数据元素中某个数据项的值,用以标识一个数据元素。

主关键字:可以唯一的标识一个数据元素的关键字。

次关键字:可以识别不止一个数据元素的关键字。

(3)查找的结果

查找成功:

找到满足条件的数据元素,作为结果,可返回数据元素在查找表中的位置,也可以返回该数据元素的具体信息。

查找失败:

无法找到满足条件的数据元素,作为结果,应该报告一些错误信息,如失败标志、失败位置。

 

3. 程序--静态查找和动态查找

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

#include "SeqList.h"

 

#define SIZE 20

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

 

void print_array(int a[], int len)

{

    int i = 0;

   

    for(i=0; i<len; i++)

    {

        printf("%d, ", a[i]);

    }

   

    printf("\n");

}

 

int static_search(int a[], int len, int key)

{

    int ret = -1;

    int i = 0;

   

    for(i=0; i<len; i++)

    {

        if( a[i] == key )

        {

            ret = i;

            break;

        }

    }

   

    return ret;

}

 

void print_list(SeqList* list)

{

    int i = 0;

   

    for(i=0; i<SeqList_Length(list); i++)

    {

        printf("%d, ", (int)SeqList_Get(list, i));

    }

   

    printf("\n");

}

 

int dynamic_search(SeqList* list, int key)

{

    int ret = -1;

    int i = 0;

   

    for(i=0; i<SeqList_Length(list); i++)

    {

        if( (int)SeqList_Get(list, i) == key )

        {

            ret = i;

           

            SeqList_Delete(list, i);

           

            break;

        }

    }

   

    return ret;

}

 

int main(int argc, char *argv[])

{

    SeqList* list = SeqList_Create(SIZE);

    int a[SIZE] = {0};

    int i = 0;

    int key = 0;

    int index = 0;

   

    srand((unsigned int)time(NULL));

   

    for(i=0; i<SIZE; i++)

    {

        a[i] = rand() % 100;

        SeqList_Insert(list, (SeqListNode*)(rand() % 100), i);

    }

   

    key = rand() % 100;

   

    printf("Static Search Demo\n");

    printf("Key: %d\n", key);

    printf("Array: \n");

    print_array(a, SIZE);

   

    index = static_search(a, SIZE, key);

   

    if( index >= 0 )

    {

        printf("Success: a[%d] = %d\n", index, a[index]);

    }

    else

    {

        printf("Failed!\n");

    }

   

    printf("Dynamic Search Demo\n");

    printf("Key: %d\n", key);

    printf("List: \n");

    print_list(list);

   

    index = dynamic_search(list, key);

   

    if( index >= 0 )

    {

        printf("Success: list[%d] = %d\n", index, key);

    }

    else

    {

        printf("Failed!\n");

    }

   

    print_list(list);

   

         return 0;

}

 

小结:

(1)      查找是程序设计领域应用最广泛的技术之一。

(2)      如何快而准的找到符合条件的数据元素是查找的技术关键。

(3)      查找表中的数据元素之间没有本质关键,但是想获得较高的查找性能必须能重新组织数据元素之间的关系。

posted @ 2019-08-11 18:51  free-锻炼身体  阅读(401)  评论(0编辑  收藏  举报