zoukankan      html  css  js  c++  java
  • 10、【查找算法】顺序查找

    顺序查找

      说明:顺序查找适合于存储结构为顺序存储或链接存储的线性表。
      基本思想:顺序查找也称为线形查找,属于无序查找算法。从数据结构线形表的一端开始,顺序扫描,依次将扫描到的结点关键字与给定值k相比较,若相等则表示查找成功;若扫描结束仍没有找到关键字等于k的结点,表示查找失败。
      复杂度分析: 
      查找成功时的平均查找长度为:(假设每个数据元素的概率相等) ASL = 1/n(1+2+3+…+n) = (n+1)/2 ;
      当查找不成功时,需要n+1次比较,时间复杂度为O(n);
      所以,顺序查找的时间复杂度为O(n)
    C++实现源码:
     1 //顺序查找
     2 #include <iostream>
     3 #include <stdlib.h>
     4 #include <ctime>
     5 
     6 using namespace std;
     7 
     8 #define MAX 100
     9 
    10 void input(int *arr)
    11 {
    12     srand((unsigned)time(NULL));
    13     for(int i = 0; i < MAX; i++)
    14     {
    15         arr[i] = rand()%100;
    16     }
    17 }
    18 
    19 void output(int *arr)
    20 {
    21     for(int i = 0; i < MAX; i++)
    22     {
    23         cout << arr[i] << "  ";
    24         if(0 == i % 10)
    25             cout << endl;
    26     }
    27     cout << endl;
    28 }
    29 
    30 int find(int *arr, int x)
    31 {
    32     for(int i = 0; i < MAX; i++)
    33     {
    34         if(x == arr[i])
    35             return i;
    36     }
    37     return 0;
    38 }
    39 
    40 int main()
    41 {
    42     int x, pos, arr[MAX];
    43     input(arr);
    44 
    45     cout << "num ... " << endl;
    46 
    47     output(arr);
    48 
    49     cout << "Enter find num : " ;
    50     cin >> x;
    51     pos = find(arr, x);
    52     if(pos)
    53         cout << "OK, " << x << "is found in pos:" << pos << endl;
    54     else
    55         cout << "Sorry!" << x << "is not found ... in num." << endl;
    56     return 0;
    57 }
  • 相关阅读:
    调用tensorflow中的concat方法时Expected int32, got list containing Tensors of type '_Message' instead.
    lstm公式推导
    RNN推导
    word2vec原理
    反向传播神经网络入门
    mac升级系统自带numpy失败解决方案
    mac安装.net core
    mac 当前位置打开终端
    docker安装配置
    KVM性能优化学习笔记
  • 原文地址:https://www.cnblogs.com/Long-w/p/9797425.html
Copyright © 2011-2022 走看看