zoukankan      html  css  js  c++  java
  • 查找->静态查找表->顺序查找(顺序表)

    文字描述

      顺序查找的查找过程为:从表中最后一个记录开始,逐个进行记录的关键字和给定值的比较,若某个记录的关键字和给定值比较相等,则查找成功,找到所查记录;反之,若直至第一个记录,其关键字和给定值比较都不等,则表明表中没有所查记录,查找不成功。

    示意图

    算法分析

      从顺序查找的过程看,Ci取决于所查记录在表中的位置。如:查找表中最后一个记录时,仅需比较一次,Ci为1;而查找表中第一个记录时,需比较n次,Ci为n。一般情况下Ci等于n-i+1。

      假设每个记录的查找概率相等,且每次都能查找成功,则平均查找长度为:

      (1/n) * [n(n+1)/2] = (n+1)/2

      假设考虑查找不成功的可能性,每个记录的查找概率也相等,则平均查找长度为:

      (1/2n) * [n(n+1)/2] + (1/2n)*n*(n+1) = [3*(n+1)]/4

    代码实现

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 
     4 #define EQ(a, b)  ((a) == (b))
     5 #define LT(a, b)  ((a) <  (b))
     6 #define LQ(a, b)  ((a) <= (b))
     7 #define MAX_SIZE 50
     8 #define DEBUG
     9 
    10 typedef int KeyType;
    11 typedef char InfoType;
    12 /*数据元素类型定义*/
    13 typedef struct{
    14     //关键字域
    15     KeyType key;
    16     //其他域
    17     InfoType otherinfo;
    18 }ElemType;
    19 /*静态查找表的顺序存储结构*/
    20 typedef struct{
    21     //数据元素存储空间基址,建表时按实际长度分配,0号单元留空
    22     ElemType *elem;
    23     //表长度
    24     int length;
    25 }SSTable;
    26 
    27 /*顺序查找算法
    28  *
    29  *在顺序表ST中顺序查找其关键字等于key的数据元素。
    30  *若找到,则函数值为该元素在表中的位置,否则为0
    31  */
    32 int Search_Seq(SSTable ST, KeyType key){
    33     //哨兵
    34     ST.elem[0].key = key;
    35     int i = 0;
    36     //从后往前找
    37     for(i=ST.length; !EQ(ST.elem[i].key, key); --i);
    38     //找不到时i为0
    39     return i;
    40 }
    41 
    42 //顺序打印顺序表中的数据元素
    43 void print_Seq(SSTable ST){
    44     int i = 0;
    45     for(i=1; i<= ST.length; i++){
    46         printf("[%d]=%d/%c; ", i, ST.elem[i].key, ST.elem[i].otherinfo);
    47     }
    48     printf("
    ");
    49 }
    50 
    51 int main(int argc, char *argv[])
    52 {
    53     int i = 0, loc = 0, key=0;
    54     ElemType arr[MAX_SIZE+1] = {0};
    55     for(i=1; i<argc; i++){
    56         arr[i].key = atoi(argv[i]);
    57         arr[i].otherinfo = 'a'+i-1;
    58     }
    59     SSTable ST;
    60     ST.length = i-1;
    61     ST.elem = arr;
    62 #ifdef DEBUG
    63     printf("输入了数据:");
    64     print_Seq(ST);
    65 #endif
    66     while(1){
    67         printf("输入待查找的key值(负值表示结束):");
    68         scanf("%d", &key);
    69         if(key < 0)
    70             break;
    71         loc = Search_Seq(ST, key);
    72         printf("key值为%d的位置在%d
    ", key, loc);
    73     }
    74     return 0;
    75 }
    顺序查找(顺序表)

    运行

  • 相关阅读:
    django 之 用户忘记密码的解决办法
    Django 富文本ckeditor 在模板中的实现
    MySQL密码的恢复方法
    sublime 快捷键
    linux 修改用户密码
    ubuntu 下重启 mysql
    python 控制浏览器模块
    读书笔记:从小工到专家(一)
    urlparse 模块
    python 标准内建函数
  • 原文地址:https://www.cnblogs.com/aimmiao/p/9469970.html
Copyright © 2011-2022 走看看