• 二分查找法C语言实现


    【问题描述】

      生成一个随机数组A[64] ,在数组中查找是否存在某个数num。

    【答案】

    #define _CRT_SECURE_NO_WARNINGS
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    //普通查找:
    int Search(int *p, int n, int num)    //找到返回下标,未找到返回-1
    {
        for (int i = 0; i < n; i++)
        {
            if (p[i] == num)
                return i;
        }
    
        return -1;
    }
    
    //冒泡排序:
    void Sort(int *p, int n)
    {
        for (int i = 0; i < n - 1; i++)
        {
            for (int j = 0; j < n - 1 - i; j++)
            {
                if (p[j] > p[j+1])
                {
                    int tmp = p[j];
                    p[j] = p[j + 1];
                    p[j + 1] = tmp;
                }
            }
        }
    }
    
    //二分查找:
    int BinarySearch(int *p, int n, int num)
    {
        int low, high, mid;
        low = 0;
        high = n - 1;
        mid = (low + high) / 2;
    
        while (low <= high)
        {
            if (num == p[mid])
                return mid;
            else if (num < p[mid])
            {
                high = mid - 1;
                mid = (low + high) / 2;
            }
            else
            {
                low = mid + 1;
                mid = (low + high) / 2;
            }
        }
    
        return -1;
    }
    
    void main()
    {
        int a[64];
        time_t tms;
        srand((unsigned int)time(&tms));    //生成随机数种子
    
        for (int i = 0; i < 64; i++)
        {
            a[i] = rand() % 100;            //0~100之间的随机数
            printf("%d
    ", a[i]);
        }
        
        //int num;
        //printf("请输入要查找的数:
    ");
        //scanf("%d", &num);
    
        int ret;
        //ret = Search(a, 64, num);
        
        Sort(a, 64);
    
        printf("排序后:
    ");
        for (int i = 0; i < 64; i++)
            printf("%d
    ", a[i]);
        int num;
        printf("请输入要查找的数:
    ");
        scanf("%d", &num);
    
        ret = BinarySearch(a, 64, num);
    
        if (ret == -1)
            printf("未找到!
    ");
        else
            printf("找到a[%d]=%d
    ",ret,num);
    
        system("pause");
    }
  • 相关阅读:
    Openssl s_time命令
    Openssl speed命令
    Openssl s_client命令
    Openssl s_server命令
    Openssl smime命令
    关于静态与非静态之具体总结
    C++游戏系列2:角色装备武器
    POJ 2398 Toy Storage(计算几何)
    Oracle核心技术 笔记(该书读得不细致,须要找时间再细读~~)
    还在为开发APP发愁? 这里就有现成通用的代码!
  • 原文地址:https://www.cnblogs.com/si-lei/p/9480781.html
Copyright © 2020-2023  润新知