• 两种查找:1无序线性查找。2有序折半查找(二分查找)


     1 #include <stdio.h>
     2 /*
     3 两种查找
     4 */
     5 #define N 10
     6 int main(void)
     7 {
     8 /*
     9 //查找1:无序数组查找,返回下标(线性查找)
    10 //思路:将需要查找的数和数组的元素逐个比较,相同返回下标,未找到返回-1
    11     int lookup(int arr[],int n,int j);
    12     int arr[N] = {1,2,3,-4,0,-8,33,11,22,7};
    13     int i,idx;
    14     
    15     printf("请输入要查找的数字,退出输入q
    ");
    16 gogogo:while(scanf("%d",&i) == 1)
    17     {
    18         idx = lookup(arr,N,i)+1;
    19         if(idx>0)
    20             printf("%d位于数组第%d位
    ",i,idx);
    21         else
    22             printf("查无此数
    ");
    23 
    24         printf("继续请输入要查找的数字,退出输入q
    ");
    25         goto gogogo;
    26     }
    27     return 0;
    28 }
    29 int lookup(int arr[],int n,int j)
    30 {
    31     int i;
    32     for(i = 0;i<n;i++)
    33     {
    34         if(j == arr[i])
    35             return i;
    36     }
    37     
    38     return -1;
    39 }
    40 */
    41 /*    
    42     //查找2:有序数组查找(折半查找)
    43     int arr[N] = {1,2,3,4,5,6,7,11,22,33};
    44     int i,idx,low,high;
    45     
    46     printf("请输入要查找的数字,退出输入q
    ");
    47 gogogo:while(scanf("%d",&i) == 1)
    48        {
    49            low = 0;
    50            high = N-1;
    51            while(low<=high)//当low和high相等的时候也要比较一次,即:查找的数字要和数组的头尾元素比较。
    52            {
    53                idx = (low+high)/2;//折半
    54                if(arr[idx]>i)
    55                    high = idx-1;
    56                else if(arr[idx]<i)
    57                    low = idx +1;
    58                else
    59                {
    60                    printf("%d位于数组第%d位
    ",i,idx+1);
    61                    break;
    62                }
    63            }
    64            if(low>high)
    65                printf("查无此数
    ");
    66            printf("继续请输入要查找的数字,退出输入q
    ");
    67            goto gogogo;
    68            
    69        }
    70        return 0;
    71 }
    72 */
  • 相关阅读:
    Java中IO流的总结
    Java常用集合体系以及相互区别
    TreeMap集合特点、排序原理
    HashMap集合
    TreeSet集合
    redis 数据类型详解 以及 redis适用场景场合
    You need tcl 8.5 or newer in order to run the Redis test
    PHP 获取二维数组中某个key的集合
    Linux 定时任务
    phpmailer邮件类
  • 原文地址:https://www.cnblogs.com/wangchaomahan/p/9599941.html
Copyright © 2020-2023  润新知